Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript sum value by key from array of array of objects

I want to sum an object value by key.
I have an array of arrays of objects.

Here:
[ 1: https://stackoverflow.com/questions/48550691/how-to-sum-all-of-values-from-specific-key-in-object][1]

I found this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var arr = [{ 'credit': 1, 'trash': null }, { 'credit': 2, 'trash': null}];
console.log(arr.reduce((total, obj) => obj.credit + total,0));
// 3

I have multiple arrays of objects, thus:

var arr2 = [ [{ 'credit': 1, 'trash': null }, { 'credit': 2, 'trash': null}],
            [{ 'credit': 3, 'trash': null }, { 'credit': 3, 'trash': null}]
          ];

for (var i=0; i<arr2.length; i++) {
    console.log( arr2[i].reduce((total, arr2[i]) => arr2[i].credit + total,0))  ;
}

When trying to access a specific array I get this error message from Google Chrome "Uncaught SyntaxError: Invalid destructuring assignment target".

The editor I am using, Sublime, highlights a syntax error.
Sublime editor highlights syntax error

I don’t know how to fix it. I have googled without success.

I want to get the total for each iteration of the loop.
In the example given, that would :
3
then
6

TIA.

>Solution :

Flatten the array, then .reduce to sum.

var arr2 = [ [{ 'credit': 1, 'trash': null }, { 'credit': 2, 'trash': null}],
            [{ 'credit': 3, 'trash': null }, { 'credit': 3, 'trash': null}]
          ];

console.log(arr2.flat().reduce((total, obj) => obj.credit + total,0));

If you don’t want to flatten, you’ll have to use a nested .reduce for the inner arrays too.

var arr2 = [ [{ 'credit': 1, 'trash': null }, { 'credit': 2, 'trash': null}],
            [{ 'credit': 3, 'trash': null }, { 'credit': 3, 'trash': null}]
          ];

console.log(
  arr2.reduce(
    (total, subarr) => total + subarr.reduce(
      (a, { credit }) => a + credit,
      0
    ),
    0
  )
);

If you don’t care about the full total but only about each subarray’s total, then just perform the simple .reduce for every element of the array.

var arr2 = [ [{ 'credit': 1, 'trash': null }, { 'credit': 2, 'trash': null}],
            [{ 'credit': 3, 'trash': null }, { 'credit': 3, 'trash': null}]
          ];

for (const subarr of arr2) {
  console.log(subarr.reduce((total, obj) => obj.credit + total,0));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading