Mona Alfonso

Mona Alfonso

Web Developer and Educator with 5+ years of experience in tech.

Explainer

The .reduce() method is used to reduce an array to a single value by applying a reducer function to each element of the array, accumulating the result. It's particularly useful for operations that involve combining or aggregating all elements of an array, such as summing numbers, flattening nested arrays, or transforming data structures. This post breaks down the .reduce() method step by step to help you better understand how the accumulator works.

Example #1: Using the Reduce Method with an Array of Numbers

Let's use a simple example of summing up all the numbers in an array:

const numbers = [1, 2, 3, 4, 5];
 
const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);
 
console.log(sum); // Output: 15

Now, let's break it down in pseudo-code: Initialize:

  • numbers = [1, 2, 3, 4, 5]
  • reduce function starts
  • accumulator = 0 (initial value provided)
  • currentValue = 1 (first element)

First iteration:

  • Operation: accumulator + currentValue
  • 0 + 1 = 1
  • accumulator becomes 1

Second iteration:

  • accumulator = 1 (result from previous iteration)
  • currentValue = 2 (second element)
  • Operation: 1 + 2 = 3
  • accumulator becomes 3

Third iteration:

  • accumulator = 3
  • currentValue = 3
  • Operation: 3 + 3 = 6
  • accumulator becomes 6

Fourth iteration:

  • accumulator = 6
  • currentValue = 4
  • Operation: 6 + 4 = 10
  • accumulator becomes 10

Fifth iteration:

  • accumulator = 10
  • currentValue = 5
  • Operation: 10 + 5 = 15
  • accumulator becomes 15

End of array reached:

  • Final value of accumulator: 15
  • This value is returned as the result of .reduce()

Finally, our sum now contains 15.

The accumulator can be thought of as a "running total" or a "rolling result" that keeps track of the combined result of all previous operations. It starts with the initial value you provide (or the first element of the array if no initial value is given) and is updated after each iteration based on the logic in your callback function.

This pattern is powerful because it allows you to perform complex operations that build upon previous results, not just simple arithmetic. You can use it for tasks like flattening arrays, grouping objects, or any operation where you need to aggregate or transform data incrementally.

Example #2: Using the Reduce Method with an Array of Strings

Here is another example, this time using an array of strings:

const words = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
 
const longestWord = words.reduce((longest, current) => {
    return current.length > longest.length ? current : longest;
});
 
console.log(longestWord); // Output: 'elderberry'

Now, let's break this down step by step in pseudo-code: Initialize:

  • words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
  • reduce function starts
  • accumulator (longest) = 'apple' (first element, as no initial value provided)
  • currentValue = 'banana' (second element)

First iteration:

  • Compare length: 'banana'.length (6) > 'apple'.length (5)?
  • True, so accumulator becomes 'banana'

Second iteration:

  • accumulator = 'banana'
  • currentValue = 'cherry'
  • Compare length: 'cherry'.length (6) > 'banana'.length (6)?
  • False, so accumulator stays 'banana'

Third iteration:

  • accumulator = 'banana'
  • currentValue = 'date'
  • Compare length: 'date'.length (4) > 'banana'.length (6)?
  • False, so accumulator stays 'banana'

Fourth iteration:

  • accumulator = 'banana'
  • currentValue = 'elderberry'
  • Compare length: 'elderberry'.length (10) > 'banana'.length (6)?
  • True, so accumulator becomes 'elderberry'

End of array reached:

  • Final value of accumulator: 'elderberry'
  • This value is returned as the result of .reduce()

Finally, longestWord now contains 'elderberry'

In this example, the accumulator (which we call longest in the callback function) keeps track of the longest word we've seen so far. We compare each word's length with the current longest, updating the accumulator only when we find a longer word.

This demonstrates how .reduce() can be used for more than just numerical calculations. It's a versatile method that can perform any kind of cumulative operation on an array.

Practice Problems

Here are 5 practice problems to help you learn how to use the .reduce() function, arranged from easiest to more complex. The first problem includes a function stub to get you started.

  1. Sum of Numbers: Calculate the sum of all numbers in an array.
const numbers = [1, 2, 3, 4, 5];
 
function sumArray(arr) {
  return arr.reduce((accumulator, currentValue) => {
    // Your code here
  }, 0);
}
 
console.log(sumArray(numbers)); // Expected output: 15
  1. Product of Numbers: Calculate the product of all numbers in an array.

  2. Flatten an Array: Given an array of arrays, flatten it into a single array. Example input: [[1, 2], [3, 4], [5, 6]] Expected output: [1, 2, 3, 4, 5, 6]

  3. Count Occurrences: Count the occurrences of each element in an array and return an object with the counts. Example input: ['a', 'b', 'a', 'c', 'b', 'a'] Expected output: { a: 3, b: 2, c: 1 }

  4. Group Objects: Given an array of objects representing people, group them by age. Example input:

const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 25 },
  { name: 'David', age: 30 }
];

Expected output:

{
  25: [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 25 }],
  30: [{ name: 'Bob', age: 30 }, { name: 'David', age: 30 }]
}
 

These problems will help you practice using .reduce() in various scenarios, from simple arithmetic to more complex data transformations. Try to solve them on your own, and if you need hints or solutions, feel free to ask!