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.

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.
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.
1Array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
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 cart2const 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];89const 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:
-
First, we have an array of objects called
shoppingCart
. Each object represents an item with two properties:item
: The name of the productprice
: The cost of that product
-
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
- The initial value is set to
-
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)
-
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 appears2const numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5];34const frequency = numbers.reduce((count, num) => {5 count[num] = (count[num] || 0) + 1;6 return count;7}, {});89console.log(frequency);10/* Output:11{121: 1, // number 1 appears once132: 2, // number 2 appears twice143: 3, // number 3 appears three times154: 2, // number 4 appears twice165: 1 // number 5 appears once17}18*/
Let's break down this example step by step:
- We start with an array of numbers that contains some duplicates:
1const numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5];
- We initialize reduce with an empty object as our accumulator:
1const frequency = numbers.reduce((count, num) => {}, {});
- 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
- Use the current number as a key in our object (
- 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...
- Initial:
- 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 arrays2const arrays = [[1, 2], [3, 4], [5, 6]];34const 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:
- We start with an array of arrays:
1const arrays = [[1, 2], [3, 4], [5, 6]];
- We initialize reduce with an empty array as our accumulator:
1const flattened = arrays.reduce((acc, curr) => acc.concat(curr), []);
- In each iteration, we:
- Concatenate the current array (
curr
) to the accumulator (acc
) - Return the updated accumulator for the next iteration
- Concatenate the current array (
- 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]
- Start:
💡 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 property2const 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];89const grouped = people.reduce((acc, person) => {10acc[person.city] = acc[person.city] || [];11acc[person.city].push(person);12return acc;13}, {});1415console.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:
- We start with an array of objects called
people
. Each object represents a person with three properties:name
: The name of the personage
: The age of the personcity
: The city the person lives in
- We initialize reduce with an empty object as our accumulator:
1const grouped = people.reduce((acc, person) => {}, {});
- 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
- Use the current person's city as a key in our object (
- 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...
- Start:
💡 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 array2const numbers = [1, 2, 3, 4, 5];34const 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:
- We start with an array of numbers:
1const numbers = [1, 2, 3, 4, 5];
- We initialize reduce with an initial value of 0 as our accumulator:
1const average = numbers.reduce((sum, num) => sum + num, 0) / numbers.length;
- In each iteration, we:
- Add the current number to the accumulator (
sum
) - Return the updated accumulator for the next iteration
- Add the current number to the accumulator (
- 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
How to Filter and Categorize Comments by Likes Using Array Reduce in JavaScript
Calculate Average Engagement Rate for Posts with High Views using JavaScript Array Methods
JavaScript: Understanding Chained Array Methods with Map, Filter, and Reduce Operations
JavaScript Array Chaining: Understanding map, filter, and reduce with Initial Value
Additional Resources
- MDN Web Docs - Array.prototype.reduce()
- JavaScript.info - Array methods
- React Documentation - Thinking in React (for seeing reduce in action with React)
Common Interview Questions
- How would you use reduce to implement map or filter?
- Can you explain the difference between reduce and reduceRight?
- 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.
Read related articles

How to use split() in JavaScript
Understand how to use split() in JavaScript to break strings into arrays fo...


What is array.at() in JavaScript?
Discover how array.at() makes working with arrays in JavaScript more intuit...


What is length in JavaScript?
Learn how to effectively use JavaScript's length property to work with stri...
