DEV Community

Kishor U.
Kishor U.

Posted on • Originally published at blackkspydo.com

Flatten Multidimensional array with Javascript

Problem

You have a multidimensional array and you want to flatten it into a single array.

const arr = [[1, 2], [3, 4], [5, 6, [7, 8, [9, 10]]]];
Enter fullscreen mode Exit fullscreen mode

Solution

Here, we use the Array.prototype.reduce() method to flatten the array. We use the Array.isArray() method to check if the current element is an array. If it is, we recursively call the flatten() function on it and concatenate the result to the accumulator. If it is not, we simply concatenate the element to the accumulator.

const flatten = arr => arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []);
Enter fullscreen mode Exit fullscreen mode

Usage

flatten(arr); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)