Flatten a Nested Array
Flatten a Nested Array is a reusable JavaScript snippet. Flattens a multi-dimensional array into a single-level array. Supports specifying depth. The full implementation: // Method 1: flat() (ES2019) const flatten = (arr, depth = Infinity) => arr.flat(depth) // Method 2: Recursive (for older environments) function flatten(arr) { return arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), [] ) } // Method 3: Generator function* flattenGen(arr) { for (const item of arr) { if (Array.isArray(item)) yield* flattenGen(item) else yield item } } // Usage flatten([1, [2, [3, 4]], 5]) // [1, 2, 3, 4, 5] This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.