In JavaScript, need to perform sum of dynamic array


Let’s say, we have an array that contains the score of some players in different sports. The scores are represented like this −

const scores = [
   {sport: 'cricket', aman: 54, vishal: 65, jay: 43, hardik: 88, karan:23},
   {sport: 'soccer', aman: 14, vishal: 75, jay: 41, hardik: 13, karan:73},
   {sport: 'hockey', aman: 43, vishal: 35, jay: 53, hardik: 43, karan:29},
   {sport: 'volleyball', aman: 76, vishal: 22, jay: 36, hardik: 24, karan:47},
   {sport: 'baseball', aman: 87, vishal: 57, jay: 48, hardik: 69, karan:37},
];

We have to write a function that takes in this array and returns a single object with value for sport key as “all” and other player key should have sum of the values that are present in different objects of the array. Therefore, let’s write the code for this function −

We will use the Array.prototype.reduce() method here to reduce the sum of scores in different sports of all the players. The code for doing this will be −

Example

const scores = [
   {sport: 'cricket', aman: 54, vishal: 65, jay: 43, hardik: 88, karan:23},
   {sport: 'soccer', aman: 14, vishal: 75, jay: 41, hardik: 13, karan:73},
   {sport: 'hockey', aman: 43, vishal: 35, jay: 53, hardik: 43, karan:29},
   {sport: 'volleyball', aman: 76, vishal: 22, jay: 36, hardik: 24, karan:47},
   {sport: 'baseball', aman: 87, vishal: 57, jay: 48, hardik: 69, karan:37},
];
const sumScores = (arr) => {
   return arr.reduce((acc, val) => {
      Object.keys(val).forEach(key => {
         if(key!== 'sport'){
            acc[key] += val[key];
         };
      });
      if(acc['sport'] !== 'all'){
         acc['sport'] = 'all';
      };
      return acc;
   });
};
console.log(sumScores(scores));

Output

The output in the console will be −

{
   sport: 'all',
   aman: 274,
   vishal: 254,
   jay: 221,
   hardik: 237,
   karan: 209
}

Updated on: 25-Aug-2020

230 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements