考虑数组:
var arr = [
{ val: 12, timestamp: 'Thu Jan 12 2017 02:00:00 GMT+0100 (CET)'},
{ val: 54, timestamp: 'Thu Jan 12 2017 02:00:00 GMT+0100 (CET)'},
{ val: 34, timestamp: 'Thu Jan 13 2017 02:00:00 GMT+0100 (CET)'},
{ val: 21, timestamp: 'Thu Jan 13 2017 02:00:00 GMT+0100 (CET)'}];
我应该使用什么来查找时间戳遇到的位置,并将val求和? 所以我会得到
result: [
{ val: 66, timestamp: 'Thu Jan 12 2017 02:00:00 GMT+0100 (CET)' }
....
]
我试图循环,但我不知道如何组合并合并?
答案 0 :(得分:0)
检查下面的代码段,您应该明白这一点。
var arr = [
{ val: 12, timestamp: 'Thu Jan 12 2017 02:00:00 GMT+0100 (CET)'},
{ val: 54, timestamp: 'Thu Jan 12 2017 02:00:00 GMT+0100 (CET)'},
{ val: 34, timestamp: 'Thu Jan 13 2017 02:00:00 GMT+0100 (CET)'},
{ val: 21, timestamp: 'Thu Jan 13 2017 02:00:00 GMT+0100 (CET)'}];
var sumArr = [];
arr.forEach(function(element) {
var sumElement = sumArr.find(function(sumElement) {
return sumElement.timestamp == element.timestamp;
});
if(sumElement) {
sumElement.val += element.val;
} else {
sumArr.push(element);
}
});
console.log(sumArr);