javascript - 循环多个数组并对相同键的值求和
问题描述
我有多个不同长度的数组,每个数组都有键值对的对象。
[{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}]
考虑到所有数组,如何求和相同日期的总时间?
解决方案
您可以按如下方式使用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
推荐阅读
- if-statement - 如何比较IF语句中的两个变量?
- reporting-services - SSRS-Report - 如何从参数中获取表名
- python - 2D-Fourier-Transformation - 正确的顺序标签?
- javascript - 从firebase javascript获取价值后运行一些东西
- java - Android ViewPager2 - 如何检测用户发起的页面更改
- spring - Spring JPA 数据未按发布顺序插入
- java - 从类名中提取 groupid 和 artifactid
- amazon-web-services - 使用 Athena 查询 S3
- generics - 未处理的异常:类型 '(T) => String' 不是类型 '(Object) => String' 的子类型
- android-studio - 如何在 Android Studio 中引用文件