Search code examples
javascripttypescriptlodash

How to calculate sum of array in JavaScript


I want to calculate sum of array data in JavaScript.

Array :

[
  {
    red_team: {
      count: 2,
      money: 3000,
    },
    blue_team: {
      count: 10,
      money: 100000,
    },
  },
  {
    red_team: {
      count: 1,
      money: 1000,
    },
    blue_team: {
      count: 100,
      money: 200000,
    },
  }
]

Expected Result :

{
  red_team: {
    count: 3,
    money: 4000,
  },
  blue_team: {
    count: 110,
    money: 300000,
  },
}

Note : red_team & blue_team is an Enum.

how can I calculate it ?


Solution

  • Spread the array into lodash's _.mergeWith(), and create a customizer that sums number, but returns undefined for all other types, so that lodash would handle all other cases:

    const data = [{"red_team":{"count":2,"money":3000},"blue_team":{"count":10,"money":100000}},{"red_team":{"count":1,"money":1000},"blue_team":{"count":100,"money":200000}}]
    
    
    const result = _.mergeWith({}, ...data, (a, b) => 
      _.isNumber(a) ? a + b : undefined
    )
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>