function steamrollArray(arr) {
//Check to see if an element is an array or not
Array.isArray(arr);
// If element is an array...then flatten it aka [2] => 2
return arr;
}
console.log(steamrollArray([1, [2], [3, [[4]]]]));
I am confused about how I can flatten an array without the flat() method. Can someone please help me out?
function steamrollArray(arr) {
let ans = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
ans.push(steamrollArray(arr[i]))
} else {
ans.push(arr[i])
}
}
return ans;
}
console.log(steamrollArray([1, [2], [3, [[4]]]]));
Thanks! I was overcomplicating it. I still can’t figure out what I am doing wrong though
Honestly, I would have thought that would return [1, 2, [3]] but I am noticing it only returns 3. I thought the push() method pushed whatever you put inside of it to the back of the array. Now I feel dumb