1

I know I can use reduce to sum the numbers of an array, like so:

let numArray = [1, 2, 3, 4].reduce((a, b) => a + b, 0);
console.log(numArray);

However, if I have an array of objects, of which one field's value is a number, how would I go about getting the sum of just that field for the objects in the array?

Say for instance for this kind of data structure:

[
  {
    name: "John Smith",
    balance: 42
  },
  {
    name: "Jane Doe",
    balance: 24
  }
]

How would I use reduce to get the sum of just the "balance" field for all the objects in the array?

Muirik
  • 6,049
  • 7
  • 58
  • 116

2 Answers2

5

Try the following:

var arr = [{name: "John Smith",balance: 42},{name: "Jane Doe",balance: 24}];

var result = arr.reduce((a,curr) => a + curr.balance, 0);

console.log(result);

You can even make a generic function for this like :

var arr = [{name: "John Smith",balance: 42, average : 20},{name: "Jane Doe",balance: 24,  average : 30}];

function getSumFromObjects(arr,prop) {
  return arr.reduce((a,curr) => a + curr[prop], 0);
}
  
//get sum of prop balance
console.log(getSumFromObjects(arr,"balance"));

//get sum of prop average
console.log(getSumFromObjects(arr,"average"));
Ivan
  • 34,531
  • 8
  • 55
  • 100
amrender singh
  • 7,949
  • 3
  • 22
  • 28
0

Always sanitize the numeric value of an object or you can have some unexpected results:

var arr = [{
  name: "John Smith",
  balance: 42
}, {
  name: "Jane Doe",
  balance: 24
}, {
  name: "Jane Doe Str",
  balance: "24"
}, {
  name: "Jane Smith Str",
  balance: "42"
}];

var okResult = arr.reduce((a, curr) => a + (curr.balance ? parseInt(curr.balance) : 0), 0);

var wrongResult = arr.reduce((a, curr) => a + curr.balance, 0);


console.log("Ok: ", okResult);
console.log("Wrong: ", wrongResult);
Matteo Gaggiano
  • 1,254
  • 15
  • 28
  • If the data is assured to contain a number for the value of the property (which will almost always be the case, data formats are rarely defined by users), i don't see a reason to sanitize. Also, if it is necessary, your way is not proper at all - `parseInt("32nd street") === 32` but if that string appears, an exception should definitely be thrown. In case it's something completely different, `NaN` will be useless aswell. Having `NaN` creep into later calculations will usually just create terrible bugs. – ASDFGerte Jun 29 '18 at 15:18