Home > Enterprise >  javascript sum value by key from array of array of objects
javascript sum value by key from array of array of objects

Time:08-31

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

Here: [ 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.

CodePudding user response:

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

  • Related