In es6, you can use the flat() method to convert a two-dimensional array into a one-dimensional array. This method will "flatten" a layer of arrays by default. You can use parameters to set the number of layers to be converted. This method It only returns a new array and does not change the original array. The syntax is "two-dimensional array.flat()".
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
Method: flat(); acceptable parameters 2,3,4...,Infinity;
flat ():
1. Responsible for converting multi-dimensional arrays ---> one-dimensional arrays. This method returns a new array and has no effect on the original data.
[1,2,[2,3],[2,2]].flat() //[1, 2, 2, 3, 2, 2]
2.flat() will only "flatten" one level by default, and the default is 1. If you want to "flatten" a multi-level nested array, you can write the parameters of the flat() method as an integer, Indicates the number of layers you want to level.
[1, 2, [3, [4, 5]]].flat() // [1, 2, 3, [4, 5]] [1, 2, [3, [4, 5]]].flat(2) // [1, 2, 3, 4, 5]
3. If you want to convert it into a one-dimensional array no matter how many levels of nesting there are, you can use the Infinity keyword as a parameter.
If the original array has gaps, the flat() method will skip the gaps.
[1, [2, [3,4]]].flat(Infinity) // [1, 2, 3, 4] [1, 2, , 4, 5].flat() // [1, 2, 4, 5]
Examples are as follows:
const a = [1, 2, 3, 4, 3]; const b = [3, 4, [5, 6]]; const c = [3, 4, [5, 6, [7, 8]]]; // 不传默认是二维数组降一维数组 console.log(a.concat(b).flat()); // 打印为[1, 2, 3, 4, 3, 3, 4, 5, 6] console.log(a.concat(c).flat(3)) // 打印为[1, 2, 3, 4, 3, 3, 4, 5, 6, 7, 8] // 如果数组嵌套太过复杂可直接传值Infinity console.log(a.concat(c).flat(Infinity)) // 打印为[1, 2, 3, 4, 3, 3, 4, 5, 6, 7, 8]
[Related recommendations:javascript video tutorial,web front-end]
The above is the detailed content of How to convert es6 two-dimensional array to one-dimensional array. For more information, please follow other related articles on the PHP Chinese website!