In JavaScript, the reduce() method is used to iterate over an array and accumulate a single result. It applies a function to each array element, resulting in a single output value.
Javascript's reduce method is one of the most complicated methods for beginners to grasp. Letβs look at how it works.
The reduce method is used to iterate over an array and accumulate to a single value. It does this by applying a function to each element of the array, resulting in a single value.
The syntax looks like this:
Array.reduce(function(accumulator, currentValue,currentIndex,array){
// logic goes here
},initialValue)
If you are using an arrow function, it will look like this
Array.reduce((accumulator, currentValue,currentIndex,array)=>{
// logic goes here
},initialValue)
accumulator
- is the value resulting from the previous iteration. If its the first iteration, the value is initialValuecurrentValue
is the current item being iteratedcurrentIndex
is the position of the current item in the arrayarray
is an optional parameter, and it represents the array the reduce method is called upon.
Letβs look at an example; suppose we have an array of numbers
numbers = [10,20,30,40]
To get the sum, we can use a for loop like this:
const numbers = [40,70,60];
let sum =0
for(let n = 0; n<numbers.length; n++){
sum+=numbers[n]
}
console.log("The sum of the numbers is:", sum); //170
However, the most optimal solution is using the reduce method.
The initialvalue will be 0, the array and the index will be optional, so the syntax will look like this:
numbers.reduce((accumulator, currentValue)=>{
accumulator+currentValue
},0)
Letβs assign the result to the variable sum and substitute our values
const sum = numbers.reduce((accumulator, item)=>{
return acc+item
})
console.log("The sum of the numbers is:", sum); //170
Letβs look at another example; suppose you are working on an e-commerce application and need to calculate the total cost of items in a cart; this scenario is a good candidate for the reduce() method.
The customer data looks like this:
const cartItems = [
{ item: 'Product 1', price: 20, quantity: 2 },
{ item: 'Product 2', price: 30, quantity: 1 },
{ item: 'Product 3', price: 15, quantity: 3 }
];
Looking at the data, we know we need to do the following:
Iterate over the array.
Calculate the total cost of each item by multiplying the price by the quantity.
Add the total cost of each item to the accumulator for each iteration.
Letβs apply the reduce () method to our array of objects.
const total = cartItems.reduce((accumulator, item)=>{
return accumulator+(item.price * item.quantity)
},0)
console.log("The total cost of items in your cart :$", total);
The output will be:
The total cost of items in your cart is:$115
Conclusion
We have covered how to use the reduce() method. Hopefully, you are now in a position to apply it in your everyday programming.