Arrays are frequently encountered in array operations, and we often need a single-layer array.
That is [1,2,[3,4,[5,[6,[7]]]] = = = [1, 2, 3, 4, 5, 6, 7], which we call the flat processing of the array.
Method One
If it's an array of pure numbers (you can also try a string), you can take advantage of the simple ToString and split methods
var arr = [1, ' A ', [3, ' 4 ', [' B ', [6,[7]]]]]console.log (arr.tostring ()]. Split (', '))// [' 1 ', ' A ', ' 3 ', ' 4 ', ' B ', ' 6 ', ' 7 ']
Method Two
Using the recursive method, if the element or array continues to be called
var arr = [1, ' A ', [3, ' 4 ', [' B ', [6,[7] ]]; function Flatten (arr) { = []; for (Let i=0,len=arr.length;i<len;i++) { if(Array.isarray (Arr[i])) { = Res.concat (Flatten (arr[i)); } Else { res.push (Arr[i]) } } return res; Console.log (Flatten (arr))//[1, ' A ', 3, ' 4 ', ' B ', 6, 7]
The above code can be simplified by using the reduce method of the array
var arr = [[[1,[2]], ' a ', [3, ' 4 ', [' B ', [6,[7]]]]function Flatten (arr) { Return Arr.reduce ((prev,item) = { return prev.concat (item)? Flatten (item): item); }, []);} Console.log (Flatten (arr))//[1, 2, ' A ', 3, ' 4 ', ' B ', 6, 7]
Both the reduce method and the Reduceright method iterate over all the items of an algebraic group and then build a final return value. The first method is a forward traversal, and the second is a backward traversal.
Accepts two parameters, the first is the function to be executed for each item, and the second is the initial value of the optional parameter as the base of the merge. The function receives 4 parameters: the previous value, the current value, the index of the item, and the array object.
Re-simplification
var arr = [[[1,[2]], ' a ', [3, ' 4 ', [' B ', [6,[7 = arr] = Arr.reduce ((a, b) = = A.concat (Array.isarray (b) ? Flat6 (b): b), []); Console.log (Flat6 (arr))//[1, 2, ' A ', 3, ' 4 ', ' B ', 6, 7]
Method Three
If it is determined that a simple two-tier nested array can use the extension operator provided by ES6
var arr = [[1,2],[3],[4,5,6]]console.log ([].concat (... arr.)]//[1, 2, 3, 4, 5, 6]
Find a better way to add it again ~ ~ ~
The flat processing method of array