What are the methods of array flattening in JavaScript
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.