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.
var arr = [1,[2,[[3,4],5],6]]; function Unid (arr) { var arr1 = (arr + '). Split (', '); Convert the array to string and then comma-delimited to array var arr2 = Arr1.map (function(x) { return number (x); }); return arr2;} Console.log (Unid (ARRA));
Law II: Using apply combined with concat, the disadvantage is that only two-dimensional to one-dimensional, multidimensional array is not.
Const 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
var arr = [1,[2,[[3,4],5],6]]; var arr2 = Arr.join (', '). Split (', '); Console.log (ARR2); // ["1", "2", "3", "4", "5", "6"]
Law IV: Recursion
var arr = [1,[2,[[3,4],5],6]]; var newArr = []; function Fun (arr) { for (var i=0;i<arr.length;i++) { if( Array.isarray (Arr[i]) {fun (arr[i]); } Else { newarr.push (arr[i]); } } } Fun (arr); Console.log (NEWARR); // [1, 2, 3, 4, 5, 6]
Law V: reduce+ recursion
Use strict '; var 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