Back to blog

How to use reduce in JavaScript - A Complete Guide with Examples

Master JavaScript's reduce method with practical examples, step-by-step explanations, and real-world use cases. Learn how to transform arrays into powerful data structures.
8 min readLogan FordLogan Ford

What is Array reduce in JavaScript?

Array.reduce is a powerful array method in JavaScript that transforms an array into a single value. Whether you're calculating totals, creating complex data structures, or processing large datasets, reduce is an essential tool in every JavaScript developer's toolkit. It's perfect for when you need to get a single value from a list of values.


Let's take a look at a simple example:

1const numbers = [1, 2, 3, 4, 5];
2const sum = numbers.reduce((acc, curr) => acc + curr, 0);
3console.log(sum); // 15

In this example, we are summing up all the numbers in the array. The reduce function takes two arguments: a callback function and an initial value. A callback function is a function that is passed as an argument to another function. The callback function takes two arguments: the accumulator (acc) and the current value (curr).


The accumulator is the value that is being accumulated, or in other words the running total. In each iteration, the accumulator holds the running total of all values processed so far. The current value (curr) is the array element being processed in the current iteration.


The initial value (0 in this case) is the starting value for the accumulator. When reduce begins executing, acc starts as 0, then becomes 1 after the first iteration, 3 after the second, 6 after the third, and so on until it reaches the final sum of 15.


💡 Pro tip: Always provide an initial value to reduce to avoid unexpected behavior with empty arrays or single-element arrays.

Syntax:

1Array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Use Cases:

The reduce function is a powerful tool for summarizing data. It's used in modern web applications for:

  • Data transformation and aggregation
  • State management in frameworks like Redux
  • Processing API responses
  • Complex calculations on arrays
  • Building data structures

Let's explore some real-world examples that you'll likely encounter in your development journey.


Example 1 - Calculate total cost of items in a shopping cart - using array reduce with an object

1// Calculate total cost of items in a shopping cart
2const shoppingCart = [
3{ item: 'Laptop', price: 999.99 },
4{ item: 'Headphones', price: 99.99 },
5{ item: 'Mouse', price: 29.99 },
6{ item: 'Keyboard', price: 59.99 }
7];
8
9const totalCost = shoppingCart.reduce((total, item) => total + item.price, 0);
10console.log(`Total cost: $${totalCost.toFixed(2)}`); // Total cost: $1189.96

Let's break down what's happening in this example step by step:

  1. First, we have an array of objects called shoppingCart. Each object represents an item with two properties:

    • item: The name of the product
    • price: The cost of that product
  2. We use the reduce method to calculate the total cost. Here's how it works:

    • The initial value is set to 0 (the second argument in reduce)
    • In each iteration, we add the current item's price to our running total
    • The total parameter keeps track of our accumulated sum
    • The item parameter represents the current object being processed
  3. Let's see how the values change in each iteration:

    • Start: total = 0
    • First iteration: 0 + 999.99 = 999.99 (Laptop)
    • Second iteration: 999.99 + 99.99 = 1099.98 (Headphones)
    • Third iteration: 1099.98 + 29.99 = 1129.97 (Mouse)
    • Final iteration: 1129.97 + 59.99 = 1189.96 (Keyboard)
  4. Finally, we format the output using:

    • Template literals (`) to create the string
    • The toFixed(2) method to ensure we show exactly 2 decimal places

💡 Pro tip: When working with financial calculations, consider using libraries like decimal.js to handle floating-point precision issues.


This is a common real-world example of using reduce to calculate a sum from an array of objects, similar to what you might find in an e-commerce application.


Example 2 - Count the frequency of numbers in an array

1// Count how many times each number appears
2const numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5];
3
4const frequency = numbers.reduce((count, num) => {
5 count[num] = (count[num] || 0) + 1;
6 return count;
7}, {});
8
9console.log(frequency);
10/* Output:
11{
121: 1, // number 1 appears once
132: 2, // number 2 appears twice
143: 3, // number 3 appears three times
154: 2, // number 4 appears twice
165: 1 // number 5 appears once
17}
18*/

Let's break down this example step by step:


  1. We start with an array of numbers that contains some duplicates:
1const numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5];

  1. We initialize reduce with an empty object as our accumulator:
1const frequency = numbers.reduce((count, num) => {}, {});

  1. In each iteration, we:
    • Use the current number as a key in our object (count[num])
    • If this number hasn't been seen before, start its count at 0
    • Add 1 to the count for this number
    • Return the updated count object for the next iteration

  1. Let's walk through how the object is built:
    • Initial: {}
    • After 1: { 1: 1 }
    • After 2: { 1: 1, 2: 1 }
    • After 2: { 1: 1, 2: 2 }
    • After 3: { 1: 1, 2: 2, 3: 1 }
    • And so on...

  1. The magic happens in this line:
1count[num] = (count[num] || 0) + 1;

Which is a shorter way of writing:

1if (count[num] === undefined) {
2 count[num] = 1;
3} else {
4 count[num] = count[num] + 1;
5}

This technique is incredibly useful when you need to count occurrences in data. You might use it to:

  • Track user interactions in analytics
  • Count character frequencies in strings
  • Analyze voting or survey results
  • Generate statistics from data sets
  • Process log files and error counts

💡 Pro tip: This pattern is commonly used in data analysis and can be extended to count any kind of object property.


Example 3 - Flatten an array of arrays

1// Flatten an array of arrays
2const arrays = [[1, 2], [3, 4], [5, 6]];
3
4const flattened = arrays.reduce((acc, curr) => acc.concat(curr), []);
5console.log(flattened); // [1, 2, 3, 4, 5, 6]

Let's break down this example step by step:


  1. We start with an array of arrays:
1const arrays = [[1, 2], [3, 4], [5, 6]];

  1. We initialize reduce with an empty array as our accumulator:
1const flattened = arrays.reduce((acc, curr) => acc.concat(curr), []);

  1. In each iteration, we:
    • Concatenate the current array (curr) to the accumulator (acc)
    • Return the updated accumulator for the next iteration

  1. Let's see how the values change in each iteration:
    • Start: []
    • After [1, 2]: [1, 2]
    • After [3, 4]: [1, 2, 3, 4]
    • After [5, 6]: [1, 2, 3, 4, 5, 6]

💡 Pro tip: For modern JavaScript, you might also consider using Array.flat() for simple flattening operations. However, reduce gives you more control over the flattening process.


This is a common real-world example of using reduce to flatten an array of arrays, similar to what you might find in an e-commerce application.


Example 4 - Grouping objects by a property

1// Group objects by a property
2const people = [
3{ name: 'Alice', age: 25, city: 'New York' },
4{ name: 'Bob', age: 30, city: 'Los Angeles' },
5{ name: 'Charlie', age: 25, city: 'New York' },
6{ name: 'David', age: 30, city: 'Los Angeles' }
7];
8
9const grouped = people.reduce((acc, person) => {
10acc[person.city] = acc[person.city] || [];
11acc[person.city].push(person);
12return acc;
13}, {});
14
15console.log(grouped);

So in this example, we are grouping the people by their city. We are using the city as the key and the person as the value.

Let's break down what's happening in this example step by step:


  1. We start with an array of objects called people. Each object represents a person with three properties:
    • name: The name of the person
    • age: The age of the person
    • city: The city the person lives in

  1. We initialize reduce with an empty object as our accumulator:
1const grouped = people.reduce((acc, person) => {}, {});

  1. In each iteration, we:
    • Use the current person's city as a key in our object (acc[person.city])
    • If this city hasn't been seen before, start its array at an empty array
    • Add the current person to the array for this city
    • Return the updated accumulator for the next iteration

  1. Let's see how the values change in each iteration:
    • Start: {}
    • After Alice: { 'New York': [{ name: 'Alice', age: 25, city: 'New York' }] }
    • After Bob: { 'New York': [{ name: 'Alice', age: 25, city: 'New York' }], 'Los Angeles': [{ name: 'Bob', age: 30, city: 'Los Angeles' }] }
    • And so on...

💡 Pro tip: This grouping pattern is extremely useful when dealing with API responses or preparing data for visualization.


This is a common real-world example of using reduce to group objects by a property, similar to what you might find in an e-commerce application.


Example 5 - Calculating the average of an array

1// Calculate the average of an array
2const numbers = [1, 2, 3, 4, 5];
3
4const average = numbers.reduce((sum, num) => sum + num, 0) / numbers.length;
5console.log(average); // 3

Let's break down what's happening in this example step by step:


  1. We start with an array of numbers:
1const numbers = [1, 2, 3, 4, 5];

  1. We initialize reduce with an initial value of 0 as our accumulator:
1const average = numbers.reduce((sum, num) => sum + num, 0) / numbers.length;

  1. In each iteration, we:
    • Add the current number to the accumulator (sum)
    • Return the updated accumulator for the next iteration

  1. Finally, we divide the total sum by the length of the array to get the average

💡 Pro tip: When calculating averages of large datasets, consider handling edge cases like empty arrays and non-numeric values.

This is a common real-world example of using reduce to calculate an average, similar to what you might find in an e-commerce application.

Practice Questions

It's best to try and solve questions related to the topic you are learning. Below are a set of practice coding challenges to help you understand how to use reduce in JavaScript. They are real-world examples of potential problems you might encounter in your day to day work.


How to Transform User Data Array into Summary Report using JavaScript Array Methods
Medium
ArraysMapFilter+1
How to Filter and Categorize Comments by Likes Using Array Reduce in JavaScript
Medium
ArraysReduceFiltering+1
Calculate Average Engagement Rate for Posts with High Views using JavaScript Array Methods
Easy
ArraysFilterReduce+1
JavaScript: Understanding Chained Array Methods with Map, Filter, and Reduce Operations
Easy
JavascriptMapFilter+1
JavaScript Array Chaining: Understanding map, filter, and reduce with Initial Value
Medium
ArraysJavascriptMap+2

Additional Resources

Common Interview Questions

  1. How would you use reduce to implement map or filter?
  2. Can you explain the difference between reduce and reduceRight?
  3. What happens if you don't provide an initial value to reduce?

Keep practicing and experimenting with reduce - it's one of the most versatile array methods in JavaScript!

Learn to code, faster

Join 650+ developers who are accelerating their coding skills with TechBlitz.

Share this article