Steamroller
The nested array is flattened. You have to consider nesting at different levels.
Array.isarray ()
Ideas:
(1) Traversing arr, if Arr[i] is an array, re-call this function to continue the loop, and then connect with the new array;
(2) If it is not an array, it is added directly into the new array;
Knowledge Points:
(1) The Array
. Concat () method is used to combine two or more arrays. Instead of changing an existing array, this method returns a new array;
(2) The Array.push () method adds one or more elements to the end of the array and returns the new length of the array;
(3) Array.isarray () determines whether the passed value is one Array
.
Code:
1 functionsteamroller (arr) {2 varNewarr=[];3 for(vari=0;i<arr.length;i++){4 if(Array.isarray (Arr[i])) {5 //if it is an array, re-call this function to continue the loop, and then connect to the new array6Newarr=Newarr.concat (Steamroller (arr[i));7}Else{8 //if it is not an array, add it directly into the new array9 Newarr.push (Arr[i]);Ten } One } A returnNEWARR; - } -Steamroller ([1, [2,222,[22,[2,[2]]], [3, [[4]]]);
Flattening of an intermediate FCC algorithm problem array