javascript - 如何根据条件对对象数组中的属性求和
问题描述
我是一名初级 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}
]
我认为这可能会涉及“减少”,但我有点不确定如何进行。任何帮助将不胜感激。
提前致谢!
解决方案
使用 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;
}, []);
推荐阅读
- python - 如何从 Flask 应用程序的 base.html 中的搜索表单提交数据?
- python-2.7 - ExcelRobot - 机器人框架骑行 - 导入问题
- paypal - 贝宝集成 - IOS/Swift
- python - 检查数据帧值是否在另一个数据帧中以及在特定日期边界或其他规范内的更好解决方案
- odata - 按 MM 关系筛选 OData
- scala - spark sql 为 when 方法抛出非直观异常
- c++ - 问题:具有约束的多个点之间的网格中的最短路径
- php - Docker 构建:扩展不通过 apk 加载:exif、gd、pdo_mysql、pecl-redis。我可以做些什么来修复我的 dockerfile?来自 php:7.4-fpm-alpine
- bash - bash - compare two lists as string , find item in list A but not in list B
- confluence - 根据输入生成内容 - 有可能吗?