Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function recursiveFlatten(array) {
  return array.reduce((accumulator, element) => {
    return Array.isArray(element) ? [...accumulator, ...recursiveFlatten(element)] : [...accumulator, element]; // Merging the two components can also happen with .concat
  }, []);
}

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();
}
node v10.15.2 linux/amd64