首页 > 解决方案 > 循环多个数组并对相同键的值求和

问题描述

我有多个不同长度的数组,每个数组都有键值对的对象。

[{date: "2018-11-26", totalHours: 2},{date: "2018-11-27", totalHours: 2}]
[{date: "2018-11-26", totalHours: 4},{date: "2018-11-27", totalHours: 2},{date: "2018-11-28", totalHours: 8}]
[{date: "2018-11-26", totalHours: 4},{date: "2018-11-27", totalHours: 2},{date: "2018-11-28", totalHours: 6},{date: "2018-11-30", totalHours: 9}]

考虑到所有数组,如何求和相同日期的总时间?

标签: javascriptreactjs

解决方案


您可以按如下方式使用reduce函数:

const x = [{ date: '2018-11-26', totalHours: 2 }, { date: '2018-11-27', totalHours: 2 }]

const sum = x.reduce((a, c) => a + c.totalHours, 0)
console.log(sum) // 4

推荐阅读