Multidimensional array dimensionality reduction is that array flattening
There are many ways to flatten arrays, but I mainly use five, as follows:
One, recursion
// One, recursion let arr = [1, [2, 3, 4, 5], [6, 7, 8, 9, [10, 11, 12, [14, 15, 16]]]] let newArr = [] const getArr=(array)=>{ ((item)=>{ // If the traversed element is not an array, put this element into the new array // Otherwise, recursively call the method again (item) ? getArr(item) : (item) }) } getArr(arr) (newArr)
2. Convert a multi-dimensional array into a string and then convert it into a one-dimensional array
let arr = [1, [2, 3, 4, 5], [6, 7, 8, 9, [10, 11, 12, [14, 15, 16]]]] ((',').split(','))
3. Methods of using arrays
(Use Infinity as depth to expand nested arrays of any depth)
() let arr = [1, [2, 3, 4, 5], [6, 7, 8, 9, [10, 11, 12, [14, 15, 16]]]] ((Infinity))
4. Use contact
var a = [1,[2],[3,4]] var result = [] for(var i=0; i<; i++){ if(a[i].constructor == Array) { result = (a[i]) }else { (a[i]) } } (result)
5. Use extension operators
The extension operator is equivalent to splitting the array into the smallest unit.
...[1,2,[3, 4]] is equivalent to becoming 1,2, [3, 4]///[ ].concat(...a) is equivalent to [ ].concat(1,2,[3, 4])
var a = [1,[2],[3,4]] var result = [] result = [].concat(...a) (result)
This is the end of this article about 5 methods for dimensional reduction of js multidimensional arrays. For more related content on dimensional reduction of js multidimensional arrays, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!