Flattening Arrays with Reduce
You'll learn how to use reduce() to transform nested arrays into a single, flat array—a powerful technique for working with complex data structures.
What Is Array Flattening?
Sometimes you have an array of arrays, like [[1, 2], [3, 4], [5]], and you need all the elements in one simple list: [1, 2, 3, 4, 5]. This process is called flattening.
Think of it like unpacking several small boxes into one large container—you're taking items from multiple nested structures and combining them into a single collection.
Using Reduce to Flatten
The reduce() method is perfect for flattening because:
- The accumulator holds your growing flat array
- Each current value is a nested array that you concatenate onto the accumulator
Here's the basic pattern:
const nested = [[1, 2], [3, 4], [5, 6]];
const flat = nested.reduce((accumulator, current) => {
return accumulator.concat(current);
}, []);
console.log(flat); // [1, 2, 3, 4, 5, 6]
Notice the initial value is []—an empty array where we'll collect all elements.
How It Works Step-by-Step
- Start:
accumulator = [],current = [1, 2]→ result:[1, 2] - Next:
accumulator = [1, 2],current = [3, 4]→ result:[1, 2, 3, 4] - Final:
accumulator = [1, 2, 3, 4],current = [5, 6]→ result:[1, 2, 3, 4, 5, 6]
Another Example
const words = [['hello', 'world'], ['from'], ['reduce']];
const allWords = words.reduce((acc, arr) => acc.concat(arr), []);
console.log(allWords); // ['hello', 'world', 'from', 'reduce']
Key Takeaway: Use reduce() with concat() to flatten one level of nested arrays by accumulating all sub-array elements into a single array—the accumulator starts as [] and grows with each concatenation.