返回匹配object.date和求和object.value的对象数组

时间:2018-03-27 03:36:44

标签: javascript reactjs ecmascript-6

返回与object.date匹配的对象数组并汇总object.value

[object[1]

2 个答案:

答案 0 :(得分:0)

返回与日期值匹配的对象数组:

const resultArray = array.filter(arrayItem => arrayItem.date === dateValue);

返回值的总和

const reducer = (summedValue, value) => summedValue + value;
const sum = array.reduce(reducer));

答案 1 :(得分:0)

要对按日期分组的值进行求和,可以使用中间对象作为映射,然后对每个日期求和:

function sumValuesGroupByDate(input) {
  var dates = {};
  input.forEach(dv => dates[dv.date] = ((dates[dv.date] || 0) + dv.value));
  return Object.keys(dates).map(date => ({date, value: dates[date]}));
}

var input = [
  {date: "2017-07-10", value: 1}, {date: "2017-07-11", value: 3},
  {date: "2017-07-10", value: 5}, {date: "2017-07-11", value: 7}
];
console.log(sumValuesGroupByDate(input));


如果你是原始的ES6 JavaScript版本的单行,那么它就是:

function sumValuesGroupByDate(input) {
  return Object.entries(input.reduce((dvs, {date: d, value: v}) => ({...dvs, [d]: (dvs[d] || 0) + v}), {})).map(([date, value]) => ({date, value}));
}

var input = [
  {date: "2017-07-10", value: 1}, {date: "2017-07-11", value: 3},
  {date: "2017-07-10", value: 5}, {date: "2017-07-11", value: 7}
];
console.log(sumValuesGroupByDate(input));