Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the methods of array flattening in JavaScript

Shulou Source: shulou.com Published: 2022-06-01 03:45:36 09月20日 Update

This article will explain in detail the methods of flattening arrays in JavaScript. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Array flattening

Array flattening refers to changing a multi-dimensional array into an one-dimensional array.

Const arr = [1, [2, [3, [4, 5]], 6]; / / = > [1, 2, 3, 4, 5, 6] method 1: use flat () const res1 = arr.flat (Infinity); method 2: use regular const res2 = JSON.stringify (arr). Replace (/\ [|\] / g,'). Split (',')

But all data types become strings.

Method 3: regular improved version const res3 = JSON.parse ('['+ JSON.stringify (arr). Replace (/\ [|\] / g,') +']); method 4: use reduceconst flatten = arr = > {return arr.reduce ((pre, cur) = > {return pre.concat (Array.isArray (cur)? Flatten (cur): cur);}, [])} const res4 = flatten (arr); method 5: function recursive const res5 = []; const fn = arr = > {for (let I = 0; I < arr.length; iota +) {if (Array.isArray (arr [I])) {fn (arr [I]);} else {res5.push (arr [I]);} fn (arr) This is the end of this article on "what are the methods of flattening arrays in JavaScript?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Method array flat article more regular good practical content function character string data article version knowledge type one-dimensional multi-dimensional recursive Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei NVidia Apple Linux Redmi