Array flattening is transforming a multidimensional array into a one-dimensional array.
Array flattening method
1, the es6 flat (the depth)
flat(depth) method, which means the depth to expand the nested array. The default is 1
The next thing you need to know is the dimensions of the array
[1.2[3.4].5].flat();
//(5) [1, 2, 3, 4, 5]
[1.2[3.4[6.7]],5].flat()
//(6) [1, 2, 3, 4, [6, 7], 5]
[1.2[3.4[6.7]],5].flat(2)
//(7) [1, 2, 3, 4, 6, 7, 5]
Copy the code
The simpler way is to simply make the target array a 1-dimensional array without knowing the dimensions of the array. The depth value is set to Infinity.
let a = [1[2.3[4[5]]]];
a.flat(Infinity); // [1,2,3,4,5] a is a 4-dimensional array
Copy the code
2, for loop
let arr1 = [1.2.3[1.2.3.4[2.3.4]]];
function flatten(arr) {
let res = [];
for (let i = 0, length = arr.length; i < length; i++) {
if (Array.isArray(arr[i])) {
res = res.concat(flatten(arr[i])); // Concat does not change the array
//res.push(... flatten(arr[i])); // The extension operator
} else{ res.push(arr[i]); }}return res;
}
flatten(arr1); //[1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
Copy the code
If it is not an array, push is performed. If it is an array, the function is executed again (recursion) until the entire array is iterated.
. And concat() can be substituted.
3. Reduce () method
The reduce() method receives a function as an accumulator, and each value in the array (from left to right) begins to shrink, eventually calculating to a single value.
var arr1 = [1.2[3], [1.2.3[4[2.3.4]]]];
function flatten(arr) {
return arr.reduce((res,next) = >{
return res.concat(Array.isArray(next)? flatten(next) : next);
},[]);
}
Copy the code
We’re using an array of reduce methods here, and notice that the reduce method, we’re passing two parameters,
The first argument is the arrow function that handles the flattening, and the second argument is an empty array that starts the traversal. (res)
4. ToString () method
No matter how deep the array is, as soon as you toString it, the structure is gone.
var arr = [[1.2.3], [4[5.6]]];
// Split the commas with split to generate an array of single strings.
let arr1 = arr.toString().split(', ') // ["1", "2", "3", "4", "5", "6"]
// Convert to a number
letarrnum = arr1.. map((item) = > parseInt(item))
console.log(arrnum) / / [6]
Copy the code
Concat () + extension operator
var arr = [1.2.3.4.5[6.7]] [].concat(... arr)//(7)[1, 2, 3, 4, 5, 6, 7]
[].concat(1.2.3.4.5[6.7[8.9]])
//(8) [1, 2, 3, 4, 5, 6, 7, Array(2)]
Copy the code
Advantages of this approach: readability; Disadvantages: Flattening of up to one depth in the item