How to flatten a (nested) array

Here are two approaches you might take to flattening a nested array. One approach is recursive and the other approach is iterative.

flattenArrayTry in REPL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function recursiveFlatten(array) {
return array.reduce((accumulator, element) => {
return Array.isArray(element) ? [...accumulator, ...recursiveFlatten(element)] : [...accumulator, element];
}, []);
}
function iterativeFlatten(array) {
const stack = [...array];
const result = [];
while (stack.length) {
const next = stack.pop();
if (Array.isArray(next)) {
stack.push(...next);
} else {
result.push(next);
}
}
return result.reverse();
}