How to convert es6 two-dimensional array to one-dimensional array

WBOY
Release: 2022-04-25 16:57:49
Original
3166 people have browsed it

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()".

How to convert es6 two-dimensional array to one-dimensional array

The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.

es6 How to convert a two-dimensional array to a one-dimensional array

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]
Copy after login

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]
Copy after login

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]
Copy after login

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]
Copy after login

[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!

Related labels:
es6
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!