Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object sum value based on properties effeicently

I do have three objects inside an array in JS like below

[{"2013-03-02T00:00": 300}, {"2013-03-01T00:00": 200},{"2013-03-02T00:00": 50}]

I want something like below as output from the above array.

[{"2013-03-02T00:00": 350} , {"2013-03-01T00:00": 200}]

It can be done by looping through and adding, are there any efficient way I can do it?

Thanks in advance.

like image 414
arnold Avatar asked Dec 05 '25 04:12

arnold


1 Answers

var myList = [{"2013-03-02T00:00": 300}, {"2013-03-01T00:00": 200},{"2013-03-02T00:00": 50}];
var result = {};
var item = null, key = null;
for(c=0; c<myList.length; c++) {
   item=myList[c];
   key = Object.keys(item)[0];
   item=item[key];

   if(!result[key]) result[key] = item;
   else result[key] += item;
}

console.log(result);

I leave it as an exercise for the reader to put the result into the requested form. (after all you should solve at least some part of your problem yourself :)

like image 197
Gung Foo Avatar answered Dec 07 '25 19:12

Gung Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!