Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding up the values of an array of objects javascript

I have an array of objects like this : const array=[{a:1, b:1} , {a:2, b:3} ,{a:1, b:1}]

i want an array like results = [{a:4 , b:5}] which is the sum of all values from the array of objects according to the key .

I tried something like this but sometimes it skipping the 1st object in the array :

       array.reduce((acc, n) => {
          for (var prop in n) {
            if (acc.hasOwnProperty(prop)) acc[prop] += n[prop];
            else acc[prop] = 0;
          }
          return acc;
        }, {})
like image 890
Bhart Supriya Avatar asked Apr 17 '26 13:04

Bhart Supriya


1 Answers

You need to initialize acc before assigning, so small modification below will work

 const array=[{a:1, b:1} , {a:2, b:3} ,{a:1, b:1}]
 const res = array.reduce((acc, n) => {
          for (var prop in n) {
          acc[prop] = acc[prop] || 0; // Need to initialize before assigning
            if (n.hasOwnProperty(prop)) {
                 acc[prop] += n[prop];
               } 
          }
          return acc;
        }, {})
console.log(res);
like image 136
Jagdish Idhate Avatar answered Apr 20 '26 02:04

Jagdish Idhate



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!