Hello! In our previous lessons, you mastered using map() to transform arrays and filter() to select specific elements. You even learned how to chain them together to perform powerful, multi-step data manipulations.
Today, we'll complete the powerful trio of fundamental array methods by learning about reduce(). While map() and filter() both return a new array, reduce() is different: its purpose is to take an entire array and distill it down to a single value.
This "single value" can be a number (like a sum or average), a string, or, most powerfully, a completely new object or array that you build up over time. By the end of this lesson, you will be able to compute a single value from an array using the reduce() method, a skill that is incredibly versatile for everything from simple calculations to complex data aggregation.
What is Reducing?
Imagine you have a list of expenses and you want to find the total amount spent. You would start at zero, and one by one, add each expense to your running total. That process of iterating through a list to arrive at one final result is exactly what reduce() is designed for.
Let's see how this works by starting with a familiar for loop and then translating it to reduce().
map, filter & reduce 🙏 Namaste JavaScript Ep. 19 🔥
The video 'map, filter & reduce' by Akshay Saini provides an excellent introduction. It starts by showing how to sum an array with a traditional loop and then refactors it to use the reduce() method, which is a perfect way to understand the concept.
Watch from 11:28 to 18:35. Pay close attention to how the sum variable in the loop version corresponds to the accumulator in the reduce() version, and how the arr[i] corresponds to the current value.
The Mechanics of reduce()
As the video explained, reduce() works by executing a callback function for each element of the array. The magic lies in how it passes values between iterations.
The reduce() method takes two arguments:
- A callback function that does the work.
- An optional initial value for the process to start with.
The callback function itself receives two main arguments:
accumulator: The value that persists and "accumulates" the result from each iteration. Think of it as thesumvariable in the loop example.currentValue: The element in the array that is currently being processed.
Here's the syntax:
const finalResult = array.reduce((accumulator, currentValue) => {
// Return the new value for the accumulator
return newAccumulatorValue;
}, initialValue);
Since you appreciate visual aids, this animation provides a perfect illustration of the data flow. On each step, the return value from the callback becomes the accumulator for the next step.
Let's Reduce! A Gentle Introduction to Javascript's Reduce Method
The article 'Let's Reduce!' from the Khan Academy Blog provides a fantastic visualization. Pay close attention to how the acc value changes with each iteration.
Read the sections 'Summing Values' and 'Visualize it'. The text explains the flow, and the GIF under 'Visualize it' brings the concept to life. Click the GIF to see the full animation.
The Crucial Initial Value
The second argument to reduce(), the initialValue, is extremely important.
- If you provide an
initialValue(like0for a sum), theaccumulatorstarts with that value, and the loop begins with the very first element of the array. - If you don't provide an
initialValue,reduce()will automatically use the first element of the array as the initialaccumulatorand start its work from the second element.
This can be convenient for simple sums, but it can lead to bugs with more complex operations or empty arrays. It is a strong best practice to always provide an explicit initialValue.
16.7: Array Functions: reduce() - Topics of JavaScript/ES6
This video from The Coding Train clearly demonstrates what happens when you provide an initial value versus when you don't. This will help solidify why it's so important.
Watch from 04:24 to 05:57. Notice how providing 10 as the initial value changes the starting point and the final result of the sum.
Test your understanding!
You have an array of numbers representing amounts you've saved each month. Use reduce() to calculate your total savings.
const monthlySavings = [50, 120, 75, 90, 200];
// Your code here...
// const totalSavings = ?
What would the code be, and what is the final totalSavings?
Show answer
const monthlySavings = [50, 120, 75, 90, 200];
const totalSavings = monthlySavings.reduce((accumulator, currentMonth) => {
return accumulator + currentMonth;
}, 0); // Start with an initial value of 0!
console.log(totalSavings); // Output: 535
Explanation:
reduceis called with an initial value of0. Theaccumulatorstarts at0.- Iteration 1:
accumulatoris0,currentMonthis50. Returns0 + 50 = 50. - Iteration 2:
accumulatoris now50,currentMonthis120. Returns50 + 120 = 170. - Iteration 3:
accumulatoris170,currentMonthis75. Returns170 + 75 = 245. - Iteration 4:
accumulatoris245,currentMonthis90. Returns245 + 90 = 335. - Iteration 5:
accumulatoris335,currentMonthis200. Returns335 + 200 = 535. - The loop finishes, and
reduce()returns the final accumulator value:535.
The Real Power: Reducing to an Object
Calculating a sum is just the beginning. The true power of reduce() is its ability to transform an array into a completely different structure, like an object. This is a common task in web development, especially when preparing data for display in a Next.js or React component.
For example, imagine you have a list of users and you want to create an object that groups them by age.
map, filter & reduce 🙏 Namaste JavaScript Ep. 19 🔥
Let's return to Akshay Saini's video for a more advanced and practical example. He demonstrates how to reduce an array of user objects into a single object that counts how many people there are of each age.
Watch from 25:37 to 31:54. The key here is to notice that the initial value is an empty object {}, and on each iteration, the logic checks for and updates properties on that accumulator object.
This pattern of starting with an empty object ({}) or an empty array ([]) as the initialValue is incredibly useful for restructuring data.
Practical Application: The Shopping Cart
Let's solidify this with another very common real-world scenario: calculating totals for a shopping cart. Here, our "single value" will be an object that contains both the total number of items and the total price.
The Complete Guide To JavaScript's .reduce() Function ...
The article 'A Complete Guide To JavaScript's .reduce() Function' provides a clear walkthrough of this exact problem.
Read the section titled 'Calculate total items and price for an ecommerce shopping cart'. Follow the code and see how the accumulator object is updated with both item quantity and price in each iteration.
Here is the code from the article. Notice how the initial value is an object that defines the shape of our final result.
const cart = [
{ itemName: 'JS course', price: 99.99, qty: 1 },
{ itemName: 'Book', price: 15.50, qty: 2 },
{ itemName: 'Keyboard', price: 75.00, qty: 1 }
];
const cartTotals = cart.reduce((acc, item) => {
// Add the quantity of the current item to the accumulator's totalItems
acc.totalItems += item.qty;
// Add the total price of the current item (price * qty) to the accumulator's totalPrice
acc.totalPrice += item.price * item.qty;
// IMPORTANT: Always return the accumulator!
return acc;
}, { totalItems: 0, totalPrice: 0.00 }); // The initial accumulator object
console.log(cartTotals);
// Output: { totalItems: 4, totalPrice: 206.49 }
Final Challenge!
In the previous lesson, we found the first names of users younger than 30 by chaining filter() and map().
const users = [
{ firstName: "akshay", lastName: "saini", age: 26 },
{ firstName: "donald", lastName: "trump", age: 75 },
{ firstName: "elon", lastName: "musk", age: 50 },
{ firstName: "deepika", lastName: "padukone", age: 26 },
];
// Chained solution:
const output = users.filter(user => user.age < 30).map(user => user.firstName);
// output is ["akshay", "deepika"]
reduce() is so powerful it can do both filtering and mapping in a single pass. Can you rewrite the code above using only reduce() to achieve the same result?
Hint: Your initial value will be an empty array ([]). Inside the callback, you'll need an if condition.
Show answer
const reduceOutput = users.reduce((acc, user) => {
// 1. The filtering step
if (user.age < 30) {
// 2. The mapping step (pushing the desired property)
acc.push(user.firstName);
}
// 3. Return the accumulator (the growing array) for the next iteration
return acc;
}, []); // Start with an empty array
console.log(reduceOutput); // Output: ["akshay", "deepika"]
Explanation: This shows the true flexibility of reduce(). We start with an empty array as our accumulator. In each iteration, we check if the user meets our condition (user.age < 30). If they do, we push their firstName into the accumulator array. If not, we do nothing. In both cases, we return the accumulator so it's available for the next iteration. While chaining filter() and map() is often more readable, this demonstrates that reduce() is the most fundamental of the array iteration methods.
Conclusion
Congratulations! You've now unlocked the reduce() method, arguably the most powerful and flexible of JavaScript's array iteration methods.
Key Takeaways:
reduce()iterates over an array to compute a single final value.- It uses an
accumulatorto carry the result from one iteration to the next. - Always providing an
initialValueis a best practice. This value can be a number (0), a string (''), an object ({}), or an array ([]), depending on what you want to create. reduce()is not just for numbers; it's a powerful tool for restructuring data, like grouping items into an object or even replacing afilter().map()chain.
Next Up
You now have a solid command of the most important array methods: forEach, map, filter, and reduce. This is a huge milestone!
In the next module, we'll shift gears slightly. We will explore several modern JavaScript (ES6+) features that make your code more expressive, powerful, and easier to read. We'll begin with Template Literals, which will revolutionize the way you work with strings.