In a previous tutorial I’ve shown you how you can flatten arrays that are indefinitely nested using recursion, concat, map and spread operator.

There’s a much simpler solution with the use of reduce.

const flatten = arrays => [].concat(...arrays.reduce((acc, curr) => {
return acc.concat(...curr);
}, []));

Open your Inspector and paste the flatten function in the console tab. Testing it with the following input, gives you the expected output:

Input: [ [ [ [1], 2], 3], [4], [], [[5]]] -> Output: [1, 2, 3, 4, 5]

However if your input to the flatten function contains strings, the result is flattened, but not as expected.

Input: [‘abc’, [‘def’, [‘ghi’, [‘jkl’]]]] ->  Output: [“a”, “b”, “c”, “def”, “ghi”, “jkl”]

If you want to flatten an array that contains strings, you can use the solution in this post