what is flattening
In one sentence, array flattening refers to turning a multidimensional array (including nesting) into a one-dimensional array
Flat ES5
const arr = [1, 2, 3, [4, 5, [6, 7]]];
const flatten = arr.toString().split(',');
console.log(flatten);
Advantages: simple, convenient, no impact on the original data
Disadvantages: The best array elements are all numbers or characters, and will not skip empty spaces
join
const arr = [1, 2, 3, [4, 5, [6, 7]]];
const flatten = arr.join(',').split(',');
console.log(flatten);
The advantages and disadvantages are the same as toString
Flat ES6
flat
const arr = [1, 2, 3, [4, 5, [6, 7]]];
const flatten = arr.flat(Infinity);
console.log(flatten);
Advantages: It will skip the empty space, return a new array, and will not modify the original array.
Disadvantages: none
The spread operator (…)
const arr = [1, 2, 3, [4, 5]];
console.log([].concat(...arr));
Advantages: simple, convenient
Disadvantage: Only one layer can be flattened
Summarize
recommended method ES6
_flat