Recursively flatten arrays in JavaScript

post header

Have you ever had to flatten an array? Did you run off to lodash or another functional library? When developing in JavaScript you’ll find having to flatten arrays is a common occurrence and not something an external library is needed for. In this post I’ll show you a couple methods to flatten arrays: starting with single level, then moving to multidimensional.

A quick side note: if your unaware of the term flattening an array, flattening an array will return a one dimensional array from a nested array.


Flatten a single level array using the spread operator

const flatten = a => [].concat(...a);

Flatten a single level array using apply

const flatten = a => [].concat.apply([], a);

Now we’ll head into flattening multidimensional arrays using recursion.

Using reduce

const flatten = a => a.reduce(
    (b, c) => b.concat(Array.isArray(c) ? flatten(c) : c), []
);

Using some

const flatten = a => a.some(Array.isArray)
  ? flatten([].concat(...a))
  : a;

-Happy coding