JavaScript

Flatten Nested Array

by @admin
12h ago
Apr 28, 2026
Public
Recursively flattens an array of arbitrary nesting depth into a single flat array. Accepts an optional depth limit — pass Infinity to flatten completely. Uses the native Array.flat when the browser supports it, otherwise falls back to a recursive reduce.
JavaScript
const flatDeep = (arr, depth = Infinity) => arr.flat(depth);

// Manual fallback for environments without Array.flat:
function flatDeepManual(arr, depth = Infinity) {
  return depth > 0
    ? arr.reduce(
        (acc, val) =>
          acc.concat(Array.isArray(val) ? flatDeepManual(val, depth - 1) : val),
        []
      )
    : arr.slice();
}

// Usage
const nested = [1, [2, [3, [4, [5]]]]];
console.log(flatDeep(nested));        // [1, 2, 3, 4, 5]
console.log(flatDeep(nested, 2));     // [1, 2, 3, [4, [5]]]
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.