首页 > 解决方案 > 如何根据条件对对象数组中的属性求和

问题描述

我是一名初级 Web 开发人员,正在寻找一些解决问题的指导。如果我遗漏了任何不可或缺的东西,请原谅,因为这是我第一次在这里发帖。

我有一个返回的一些数据数组,如下所示:

[
 {x: Date(1234), y: 0}
 {x: Date(1235), y: 0}
 {x: Date(1236), y: 300}
 {x: Date(1237), y: 300}
 {x: Date(1238), y: 300}
 {x: Date(1239), y: 300}
 {x: Date(1240), y: 300}
 {x: Date(1241), y: 0}
 {x: Date(1242), y: 0}
 {x: Date(1243), y: 0}
]

如果可能的话,我想返回一个新数组,其中所有连续的 'y' 值 > 0 相加。在新数组中,求和值应与求和项的第一个“x”值相关联,如下所示:

[
 {x: Date(1234), y: 0}
 {x: Date(1235), y: 0}
 {x: Date(1236), y: 1500}
 {x: Date(1241), y: 0}
 {x: Date(1242), y: 0}
 {x: Date(1243), y: 0}
]

我认为这可能会涉及“减少”,但我有点不确定如何进行。任何帮助将不胜感激。

提前致谢!

标签: javascriptarraysreduce

解决方案


使用 reduce,您可以执行以下操作:https ://jsbin.com/leladakiza/edit?js,console

var input = [
 {x: Date(1234), y: 0},
 {x: Date(1235), y: 0},
 {x: Date(1236), y: 300},
 {x: Date(1237), y: 300},
 {x: Date(1238), y: 300},
 {x: Date(1239), y: 300},
 {x: Date(1240), y: 300},
 {x: Date(1241), y: 0},
 {x: Date(1242), y: 0},
 {x: Date(1243), y: 0},
];

var output = input.reduce(function (acc, val) {
  var lastIndex = acc.length - 1;
  if (val.y <= 0 || lastIndex < 0 || acc[lastIndex].y <= 0) {
    acc.push(val);
  } else {
    acc[lastIndex].y += val.y;
  }
  return acc;
}, []);

推荐阅读