JavaScript Array .reduce()
method
The JavaScript array .reduce()
method is commonly used to get the sum of the array of numbers. It iterates through each item of the array and using the built-in reducer function it will import a singular item.
Array .reduce()
Method Syntax
This is how you can use the the .reduce()
method.
array.reduce((accumulator, currentValue, currentIndex, arrayCopy) => {
// run your test here and make sure to import something
}, initialValue)
accumulator
- this serves as the accumulated value, also referred to as the previous value.currentValue
- the current iterated item of the array.currentIndex
- the current index of the iterated item.arrayCopy
- a copy of the reference array.initialValue
- this serves as an initial value passed to the accumulator before the code runs. If left blank, the value of the first iterated item would be the initial value.
Example: Array .reduce()
Method on Array of Objects
Using the example data below where we have an array of strawHats
that contains objects
with attributes of name, bounty and power.
const strawHats = [
{ name: "Luffy", bounty: 1500, power: 100 },
{ name: "Zoro", bounty: 500, power: 90 },
{ name: "Sanji", bounty: 400, power: 85 },
]
Example #1: Get the total bounty of this group.
const totalBounty = strawHats.reduce((accumulator, current) => {
let sum = accumulator + current.bounty;
return sum;
}, 0)
console.log(`total bounty 💰 ${totalBounty}`)
Example #2: Get the total power of strawhats.
const totalPower = strawHats.reduce((prev, curr) => prev + curr.power, 0)
console.log(`total power 🔥 ${totalPower}`)
Example #3: Who's the most powerful character of the group.
const boss = strawHats.reduce((previous, current) => {
if (current.power > previous.power) {
return current;
}
return previous;
})
console.table(boss)
Notice in the examples that we changed the parameter names like accumulator
, then we used prev
, and lastly previous
, thats because you can name it whatever you want, just make sure you know the proper order of parameters based on the array .reduce() syntax
.
Watch Tutorial
Here's a quick video tutorial about the JavaScript array .reduce()
method.