当值在循环中相遇时组合值

时间:2017-01-13 19:29:09

标签: javascript

考虑数组:

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)' }
 ....
] 

我试图循环,但我不知道如何组合并合并?

1 个答案:

答案 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);