Flatten Multidimensional Array with Javascript
Published Oct 10, 2022
Problem
You have a nested array structure and you want to convert it into a single-dimensional array.
const arr = [[1, 2], [3, 4], [5, 6, [7, 8, [9, 10]]]]
Solution
The approach uses Array.prototype.reduce() combined with recursion. The method checks whether each element is an array using Array.isArray(). For arrays, it recursively flattens nested structures; for non-arrays, it appends values directly.
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]
