2

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?

1
  • use b.balance Commented Jun 29, 2018 at 14:58

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

if balance is undefined or not a number format the result will be 042undefined24
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);

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.