I have multiple arrays of objects with a string property "CountType" and a number property "ItemCount".
The objects must be added up to calculate the total of all items by "CountType" property.
For example, I need to know the total number of Volumes, Sheets, Photos, etc.
Attempt #1: This code I attempted returns 0. Possibly that is because I need to loop through the outer array to do the comparison across the nested arrays.
function sumByProperty(items, prop) {
if (items == null) {
return 0;
}
return items.reduce(function (a, b) {
return b[prop] == null ? a : a + b[prop];
}, 0);
}
INPUT
Item count
[
[
{"CountType":"Volumes","ItemCount":3},
{"CountType":"Sheets","ItemCount":6},
{"CountType":"Photos","ItemCount":3},
{"CountType":"Boxes","ItemCount":1},
{"CountType":"Other","ItemCount":2}
],
[
{"CountType":"Volumes","ItemCount":1},
{"CountType":"Sheets","ItemCount":1},
{"CountType":"Photos","ItemCount":3},
{"CountType":"Boxes","ItemCount":0},
{"CountType":"Other","ItemCount":1}
],
[
{"CountType":"Volumes","ItemCount":1},
{"CountType":"Sheets","ItemCount":0},
{"CountType":"Photos","ItemCount":3},
{"CountType":"Boxes","ItemCount":4},
{"CountType":"Other","ItemCount":5}
]
]
DEISRED OUTPUT
Total count
[
{"CountType":"Volumes","ItemCount":5},
{"CountType":"Sheets","ItemCount":7},
{"CountType":"Photos","ItemCount":9},
{"CountType":"Boxes","ItemCount":5},
{"CountType":"Other","ItemCount":8}
]
UPDATE: Here is how I am trying to run the function:
sumByPropertyfunction seems fine. Please show us how you are calling it on the input