TypeScript: sum of object properties within an array

If we need to sum a simple array, we can use the reduce method, that executes a reducer function (that you provide) on each member of the array resulting in a single output value.

For example:

let sum = [1, 2, 3].reduce((a, b) => a + b, 0);
// expected output: 6

But if we have an objects array like the following:

let itemArray = [
  { id: 1, value: 23 },
  { id: 2, value: 30 },
  { id: 3, value: 7 },
  { id: 4, value: 21 }

We need to use the map method (that creates a new array with the results of calling a provided function on every element in the calling array) to obtain another objects array that contains only this properties values,  and after this we can use the reduce method:

let sum: number = itemArray.map(a => a.value).reduce(function(a, b)
  return a + b;
// expected output: 81

Onother solution is to use the foreach iterator:

let sum: number = 0;
itemArray.forEach(a => sum += a.value);
console.log(sum );
// expected output: 81


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s