Methods a
Flat () Using ES6 extension method for arrays
1) Flatten one layer by default
[1.2[3.4[5.6]]].flat()
//[1, 2, 3, 4, [5,6]]
Copy the code
2) Receive a numeric parameter stating how many layers to flatten
[1.2[3.4[5.6]]].flat(2)
//[1, 2, 3, 4, 5, 6]
Copy the code
3) No matter how many dimensions of the array are flattened into a one-dimensional array, accept Infinity as a parameter
[1.2[3.4[5.6]]].flat(Infinity)
//[1, 2, 3, 4, 5, 6]
Copy the code
Method 2
If the current element is not an array, the current element concat is linked after the previous element. If the current element is an array, the recursive fn is used to concat each item into an array
// Use reduce
function fn(arr){
return arr.reduce((prev,cur) = >{
return prev.concat(Array.isArray(cur)? fn(cur):cur) },[]) }Copy the code
Reduce parameters (total,currentValue, index, ARR) Total (required) : CurrentValue (required) : current element traversal index (optional) : index of the current element traversal ARR (optional) : array object to which the current element belongs
Using this idea, you can also use loops instead of reduce functions
function fn(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(flatten(arr[i]));
} else{ result.push(arr[i]); }}return result;
}
Copy the code
Can also be overwritten with the extension operator
function fn(arr){
let arr1 = [];
let bStop = true;
arr.forEach((val) = >{
if(Array.isArray(val)){ arr1.push(... val); bStop =false
}else{
arr1.push(val)
}
})
if(bStop){
return arr1;
}
return fn(arr1)
}
Copy the code
Methods three
let arr = [1.2.3[4.5]]
let arr1 = arr.toString().split(', ').map((val) = >{
return parseInt(val)
})
console.log(arr1)/ / [1, 2, 3, 4, 5]
Copy the code
Methods four
Check whether the current array is an array of more than two dimensions (that is, whether the elements in the array are an array). If it is a one-dimensional array, return the current array. If it is a two-dimensional array or more, use Apply to expand one layer and keep expanding to a one-dimensional array.
function fn(arr){
while(arr.some(item= > Array.isArray(item))){
arr = [].concat.apply([],arr);
}
return arr;
}
Copy the code