-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16-steamroller.js
24 lines (22 loc) · 916 Bytes
/
16-steamroller.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
Steamroller:
Flatten a nested array. You must account for varying levels of nesting.
- steamrollArray([[["a"]], [["b"]]]) should return ["a", "b"].
- steamrollArray([1, [2], [3, [[4]]]]) should return [1, 2, 3, 4].
- steamrollArray([1, [], [3, [[4]]]]) should return [1, 3, 4].
- steamrollArray([1, {}, [3, [[4]]]]) should return [1, {}, 3, 4].
- Your solution should not use the Array.prototype.flat() or Array.prototype.flatMap() methods.
*/
function steamrollArray(arr) {
let finalArr = [];
arr.forEach(item =>
Array.isArray(item)
? finalArr.push(...steamrollArray(item))
: finalArr.push(item));
return finalArr;
}
console.log(steamrollArray([1, [2], [3, [[4]]]]));
console.log(steamrollArray([[["a"]], [["b"]]]));
console.log(steamrollArray([1, [], [3, [[4]]]]));
console.log(steamrollArray([1, [], [3, [[4]]]]));
console.log(steamrollArray([1, {}, [3, [[4]]]]));