Get the App
SLTechnology News&Howtos  ›  Development  › 

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

Shulou Source: shulou.com Published: 2022-05-31 18:40:08 09月30日 Update

This article introduces the knowledge of "how to convert es6 two-dimensional array to one-dimensional array". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

In es6, you can use the flat () method to convert a two-dimensional array into an one-dimensional array, which "flattens" a layer array by default, and can use parameters to set the number of layers to be converted. This method only returns a new array and does not change the original array. The syntax is "two-dimensional array .flat ()".

This tutorial operating environment: windows10 system, ECMAScript version 6. 0, Dell G3 computer.

How to transfer an es6 two-dimensional array to an one-dimensional array

Method: flat (); acceptable parameter 2, 3, 4, 4, and Infinity

Flat ():

1. Responsible for the multidimensional array-> one-dimensional array. This method returns a new array with no effect on the original data.

[1pr 2, [2pr 3], [2pr 2] .flat () / / [1rect 2, 2pm 3, 2pm 2]

2.flat () only "flattens" one layer by default, and defaults to 1. If you want to "flatten" a nested array of multiple layers, you can write the parameters of the flat () method as an integer, indicating the number of layers you want to flatten.

[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 to an one-dimensional array no matter how many layers of nesting you have, you can use the Infinity keyword as a parameter.

If there are spaces in the original array, the flat () method skips them.

[1, [2, [3jue 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]; / / the default is two-dimensional array console.log (a.concat (b). Flat ()) / print as [1, 2, 3, 4, 3, 3, 3, 4, 5, 6] console.log (a.concat (c). Flat (3)) / / print as [1, 2, 3, 4, 3, 3, 4, 5, 6, 7, 8] / / if the array nesting is too complex, you can directly pass the value Infinity console.log (a.concat (c) .flat (Infinity)) / / print as [1,2) 3, 4, 3, 3, 4, 5, 6, 7, 8] how to transform an es6 two-dimensional array into an one-dimensional array. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Array one-dimensional method two-dimensional parameter content more knowledge vacancy complex practical successful next key keyword dilemma multi-layer actual situation tutorial Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Linux Docker MariaDB NVidia