Skip to content
GreenSnippets

Flatten nested arrays

Flatten arrays to any depth with a small recursive helper that mirrors Array.prototype.flat.

JavaScript
function flatten(array, depth = Infinity) {
  return depth < 1
    ? array.slice()
    : array.reduce(
        (acc, item) => acc.concat(Array.isArray(item) ? flatten(item, depth - 1) : [item]),
        [],
      );
}

Example / expected output

Output
flatten([1, [2, [3, [4]]]])    // [1, 2, 3, 4]
flatten([1, [2, [3, [4]]]], 1) // [1, 2, [3, [4]]]

How it works

array.flat(depth) is built in and Infinity flattens everything. The recursive version below shows the idea and lets you see how depth is consumed one level at a time.