This is the purpose of the algorithm:
Flatten a nested array. You must account for varying levels of nesting.
Right now my solution works, but I want it to be more efficient.
For example. Right now it is limited to the amount of depth I have put in my code.
How can I check how many arrays there are inside of each of the arrays without writing so much repetitive code?
Any ideas will be much appreciated!
Thanks.
Your code so far
function steamrollArray(arr) {
let newArr = [];
for(let i = 0; i < arr.length; i++){
if(Array.isArray(arr[i])){
for(let j = 0; j < arr[i].length; j++){
if(Array.isArray(arr[i][j])){
for(let y = 0; y < arr[i][j].length; y++){
if(Array.isArray(arr[i][j][y])){
for(let x = 0; x < arr[i][j][y].length; x++){
if(!Array.isArray(arr[i][j][y][x])){
newArr.push(arr[i][j][y][x]);
}
}
} else {
newArr.push(arr[i][j][y]);
}
}
} else {
newArr.push(arr[i][j]);
}
}
} else {
newArr.push(arr[i]);
}
}
return newArr;
console.log(newArr);
}
steamrollArray([1, 2, [3], [1, 2]]);
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
.
Link to the challenge: