Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript cumulate an array of object to an array of object

I have an array of objects:

var myArray = [
    {
        "date" : "03/01/2017",
        "value" : 2
    },  {
        "date" : "04/01/2017",
        "value" : 6
    },  {
        "date" : "05/01/2017",
        "value" : 4
    }
];

I need to cumulate the value and keep the same array with updated values

The result would look like this

var myArray = [
    {
        "date" : "03/01/2017",
        "value" : 2
    },  {
        "date" : "04/01/2017",
        "value" : 8 //(2+6)
    },  {
        "date" : "05/01/2017",
        "value" : 12 //(2+6+4)
    }
];

I am aware that this exists

[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
  return accumulator + currentValue;
});

But I cannot find an example with object returning also objects

like image 556
Weedoze Avatar asked Jan 04 '17 15:01

Weedoze


2 Answers

Use the this argument of Array.prototype.forEach to accumulated the value - see demo below:

var myArray=[{"date":"03/01/2017","value":2},{"date":"04/01/2017","value":6},{"date":"05/01/2017","value":4}];

myArray.forEach(function(e){
  this.count = (this.count || 0) +  e.value;
  e.value = this.count;
},Object.create(null));

console.log(myArray);
.as-console-wrapper{top:0;max-height:100%!important;}
like image 121
kukkuz Avatar answered Nov 14 '22 22:11

kukkuz


You can use map() and Object.assign() to make copy of objects.

var myArray = [{
  "date": "03/01/2017",
  "value": 2
}, {
  "date": "04/01/2017",
  "value": 6
}, {
  "date": "05/01/2017",
  "value": 4
}];

var result = myArray.map(function(o) {
  var obj = Object.assign({}, o)
  obj.value = this.total += o.value
  return obj
}, {total: 0})

console.log(result)
like image 41
Nenad Vracar Avatar answered Nov 14 '22 22:11

Nenad Vracar