Using Reduce

Posted on

in

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

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

March 2024
M T W T F S S
 123
45678910
11121314151617
18192021222324
25262728293031