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 need to write a function that takes this array and returns a single object with the sport key as "all" and other player keys should have the sum of their values across all sports.

Using Array.reduce() Method

We will use the Array.prototype.reduce() method to calculate the sum of scores for all players across different sports:

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] = (acc[key] || 0) + val[key];
      }
    });
    acc['sport'] = 'all';
    return acc;
  }, {});
};

console.log(sumScores(scores));
{
  sport: 'all',
  aman: 274,
  vishal: 254,
  jay: 221,
  hardik: 237,
  karan: 209
}

How It Works

The function works by:

  • Using reduce() to iterate through each sport object
  • For each object, iterating through all keys using Object.keys()
  • Skipping the 'sport' key and accumulating values for player keys
  • Setting the sport value to 'all' in the final result
  • Using (acc[key] || 0) to handle undefined values safely

Alternative Approach Using Object.entries()

Here's another way to achieve the same result using Object.entries():

const sumScoresAlt = (arr) => {
  const result = { sport: 'all' };
  
  arr.forEach(sportData => {
    Object.entries(sportData).forEach(([key, value]) => {
      if (key !== 'sport') {
        result[key] = (result[key] || 0) + value;
      }
    });
  });
  
  return result;
};

console.log(sumScoresAlt(scores));
{
  sport: 'all',
  aman: 274,
  vishal: 254,
  jay: 221,
  hardik: 237,
  karan: 209
}

Conclusion

Both approaches effectively sum dynamic array properties using JavaScript's built-in methods. The reduce() method provides a functional programming approach, while the forEach() method offers a more imperative style for the same result.

Updated on: 2026-03-15T23:18:59+05:30

386 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements