Method One: Use the array map () method, which runs the given function for each item in an array, and returns a list of the results of each function call.
Let arr = [1, [2, [[3,4],5],6]];function Onedimensionalarray (arr) { "). Split (','// Convert the array to a string and then comma-delimited to array let arr2 = Arr1.map (function (x ) {return number (x); }); return arr2;} Console.log (Onedimensionalarray (arr));
Law two: Using apply combined with concat, the disadvantage is that only two-dimensional to one-dimensional, multi-dimensional array is wrong.
Let arr = [1,[2,3],[4,5]];console.log ([].concat.apply ([],arr)];
Method Three: Convert an array to a string and then to an array, with the disadvantage that each item in the array is a string
Let arr = [1,[2,[[3,4],5],6]];let arr2 = Arr.join (', '). Split (', '); Console.log (ARR2);//["1", "2", "3", "4", "5", "6"]
Or
Let C=[1,3,4,5,[6,[0,1,5],9],[2,5,[1,5]],[5]];
Console.log (C.tostring (). Split (', '))
Law IV: Recursion
Let arr = [1, [2, [[3456= [];function Onedimensionalarray (arr) { for0; i < arr.length; i++) { if (Array.isarray (Arr[i])) { Onedimensionalarray (arr[i]); Else { newarr.push (arr[i]); } // [1, 2, 3, 4, 5, 6]
Law V: reduce+ recursion
Use strict '; Let arr = [1,[2,[[3,4],5],6]]; Const FLATTEN = arr = Arr.reduce ( (acc,val) = Acc.concat (Array.isarray (val)? Flatten (val): Val), [] ) Console.log (Flatten (arr));//[1, 2, 3, 4, 5, 6]
A multidimensional array to one dimension in JS