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);
console.log(sum);
// 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;
});
console.log(sum);
// 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

Laisser un commentaire