-3

consider the array:

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

What should i use to find where the timestamp meet, and sum the val ? so I would get

result: [
 { val: 66, timestamp: 'Thu Jan 12 2017 02:00:00 GMT+0100 (CET)' }
 ....
] 

I tried to loop, but I cannot know to how group and merge?

Ilanus
  • 6,690
  • 5
  • 13
  • 37

1 Answers1

0

Check the snippet below, you should get the idea.

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);
Mateusz Woźniak
  • 1,479
  • 1
  • 9
  • 10