Flatten Multidimensional array with Javascript

Blackkspydo

0 views 0 reactions 2022-10-10

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]]]];

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), []);

Usage

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

References

Leave a reaction if you liked this post! 🧡

Subscribe to the newsletter

Get emails from me about Lorem ipsum dolor sit, amet consectetur adipisicing elit. Libero, ducimus..

3 subscribers including my Mom – 23 issues