ES6 `.reduce` helper explained

Photo by Joshua Aragon on Unsplash

One of the most powerful but often misunderstood array helpers in JavaScript is the .reduce method. Its primary function is to take an array and reduce it down to a single value. It can be incredibly versatile, and understanding how it works can significantly improve your JavaScript coding skills.

Basic Functionality

What It Does

The .reduce method takes a function and an initial value for the accumulator. It then goes through each item in the array, applying the function, and returns a single, reduced value at the end.

const numbers = [1, 2, 3];
const sum = numbers.reduce((accumulator, current) => accumulator + current, 0);
// Result: sum is 6

The Role of the Accumulator

Starting Point

The accumulator is like a “memory variable” that keeps track of the operations performed on each array element. Its initial value is specified as the second argument to the .reduce function. In the example above, the initial value is 0.

During Iteration

As .reduce iterates through the array, the accumulator’s value can change based on the logic you provide. Here’s how it works step-by-step for the above example:

  1. First Iteration: Accumulator is 0, Current is 1. 0 + 1 = 1. New Accumulator: 1
  2. Second Iteration: Accumulator is 1, Current is 2. 1 + 2 = 3. New Accumulator: 3
  3. Third Iteration: Accumulator is 3, Current is 3. 3 + 3 = 6. New Accumulator: 6

Final Value

The final value of the accumulator is what .reduce returns. In our example, it returns 6.

Practical Uses

The .reduce method is not just for numbers. You can use it to flatten arrays, count occurrences of items, or even manipulate objects.

Flattening an Array

const arrays = [[1, 2], [3, 4], [5, 6]];
const flat = arrays.reduce((acc, curr) => [...acc, ...curr], []);
// Result: flat is [1, 2, 3, 4, 5, 6]

Counting Occurrences

const names = ['Alice', 'Bob', 'Alice', 'Charlie'];
const count = names.reduce((acc, name) => {
acc[name] = (acc[name] || 0) + 1;
return acc;
}, {});
// Result: count is { Alice: 2, Bob: 1, Charlie: 1 }

Summary

Understanding the accumulator is key to mastering the .reduce method in JavaScript. It serves as a “memory” that holds intermediate results as you loop through the array, allowing you to reduce the array to a single value effectively.

,