There is an array like this:
Const arr = [1, 2, 3, 4, 5), 6], 7], 8]
When we need to turn it into a one-dimensional array, we use flattening.
The first method is flat().
console.log(arr.flat(3))
Copy the code
The results are as follows
Second: use regular expressions
Const res1 = JSON. Stringify (arr) replace (/ \ [| \] / g, "). The split (', ') / / is an array of strings, will convert it to digital. console.log(JSON.parse('[' + res1 + ']'))Copy the code
Third: use recursion
Iterate over each item in the array, while that item is still an array, until it’s not an array and pushes it into the new array
const arr1 = []
const fn = (arr) => {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
fn(arr[i])
} else {
arr1.push(arr[i])
}
}
}
fn(arr)
console.log(arr1)
Copy the code
Use the reduce
const newArr = (arr) => {
return arr.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? newArr(cur) : cur)
}, [])
}
console.log(newArr(arr))
Copy the code