Flattening Arrays with Reduce
You'll learn how to use reduce to transform nested arrays into a single flat array, a technique that was essential before modern JavaScript added built-in flattening methods.
What Is Array Flattening?
Imagine you have an array of arrays (nested structure) and you want to merge them all into one continuous array. That's flattening—turning [[1, 2], [3, 4], [5]] into [1, 2, 3, 4, 5].
Before Array.prototype.flat existed, reduce was the go-to solution for this problem.
How Reduce Flattens Arrays
The key insight: use reduce to concatenate each sub-array onto an accumulating result array. Start with an empty array as your initial value, then use the concat method to merge each nested array into it:
const nested = [[1, 2], [3, 4], [5, 6]];
const flat = nested.reduce((acc, current) => {
return acc.concat(current);
}, []);
console.log(flat); // [1, 2, 3, 4, 5, 6]
Here's what happens step-by-step:
- Start:
acc = [] - First iteration:
acc.concat([1, 2])→[1, 2] - Second iteration:
[1, 2].concat([3, 4])→[1, 2, 3, 4] - Third iteration:
[1, 2, 3, 4].concat([5, 6])→[1, 2, 3, 4, 5, 6]
With arrow functions, this becomes even more concise:
const flat = nested.reduce((acc, arr) => acc.concat(arr), []);
Think of it like emptying boxes: each iteration takes items from one box (nested array) and places them into your main container (accumulator).
Key Takeaway: Before flat() existed, reduce with concat was the standard way to flatten one level of nested arrays, accumulating elements from each sub-array into a single result array.