如何计算 JavaScript 中数组的总和

How to calculate sum of array in JavaScript

我想计算 JavaScript 中数组数据的总和。

数组:

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

预期结果

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

注意: red_team & blue_team 是枚举。

如何计算?

根据上面的评论,有无数种方法可以做到这一点。我刚想到一个(诚然相当冗长)

详细解决方案:

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

function sumByKeyAndProperty(arr, key, property){
  let sum = 0
  arr.forEach((obj) => {
    sum+=obj[key][property]
  })
  return sum
}

returnObj = {
  red_team: {
    count: sumByKeyAndProperty(arr, 'red_team', 'count'),
    money: sumByKeyAndProperty(arr, 'red_team', 'money'),
  },
  blue_team: {
    count: sumByKeyAndProperty(arr, 'blue_team', 'count'),
    money: sumByKeyAndProperty(arr, 'blue_team', 'money'),
  }
}

console.log(returnObj)

将数组散布到 lodash 的 _.mergeWith() 中,并创建一个对数字求和的自定义程序,但对所有其他类型 returns undefined,以便 lodash 处理所有其他情况:

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>