循环多个数组并求和相同键的值

时间:2018-11-29 11:05:00

标签: javascript reactjs

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

[{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}]

在考虑所有数组的情况下,如何求和相同日期的总小时?

3 个答案:

答案 0 :(得分:0)

您可以按以下方式使用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

答案 1 :(得分:0)

您可以首先使用扩展语法创建一个数组,然后使用reduce方法来计算总和。

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

let sum = [...a, ...b, ...c].reduce((r, {date, totalHours}) => {
  if(!r[date]) r[date] = totalHours;
  else r[date] += totalHours;
  return r;
}, {})

console.log(sum)

答案 2 :(得分:0)

let a = [
    ...[{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}]
];

let result = {};

a.forEach((i) => {
  result[i.date] = result[i.date] || { date: i.date, totalHours: 0 };
  result[i.date].totalHours += i.totalHours;
});

result = Object.values(result)
console.log(result);