-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflatNestedArray.js
47 lines (45 loc) · 998 Bytes
/
flatNestedArray.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller
*
* Flatten a nested array. You must account for varying levels of nesting.
*
* Your solution should not use the Array.prototype.flat() or Array.prototype.flatMap() methods.
*/
function steamrollArray(arr) {
return reduceArray(arr)
}
const reduceArray = (arr) => arr.reduce((acc, curr) => {
if (!Array.isArray(curr)) {
return [...acc, curr]
} else {
return [...acc, ...reduceArray(curr)]
}
}, [])
steamrollArray([1, [2],
[3, [
[4]
]]
]);
steamrollArray([
[
["a"]
],
[
["b"]
]
]) // ["a", "b"]
steamrollArray([1, [2],
[3, [
[4]
]]
]) // [1, 2, 3, 4]
steamrollArray([1, [],
[3, [
[4]
]]
]) // [1, 3, 4]
steamrollArray([1, {},
[3, [
[4]
]]
]) // [1, {}, 3, 4]