Flatten nested arrays
Flatten arrays to any depth with a small recursive helper that mirrors Array.prototype.flat.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
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
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.
Related snippets
- JavaScript Tested
Remove duplicates from an array
Deduplicate primitives with a Set, or objects by a key or computed value, keeping the first occurrence.
- JavaScript Tested
Sort an array by multiple keys
Sort objects by one field, then break ties with another, with ascending or descending order per field.
- TypeScript Tested
Non-empty array type
Encode "at least one element" in the type so head, max and similar functions never see an empty array.
- PHP Tested
Group an array of records by a key
Turn a flat list of associative arrays into groups keyed by a field or callback.

