Reduce is used somewhat similar to ‘map’
const scores = [55,17,138,3,18];
const totalScore = scores.reduce(
(previousScore,currentScore,index)=> previousScore + currentScore,0
);
console.log(totalScore); // returns 231
Zero is set as the initial value and then it goes through the array and adds each value (in this example the currentScore) to the totalScore which becomes the new ‘previousScore’.
Here’s a more useful example:
const refactoredUsers = [
{ id: 1, name: "Mark" },
{ id: 2, name: "James" },
{ id: 3, name: "Ben" }
].reduce((prev, currentUser) => {
return {
[currentUser.id]: currentUser.name,
...prev
}
}, {})
console.log(refactoredUsers);
//returns
{
1: Mark,
2: James,
3: Ben
}
Leave a Reply