Borislav Hadzhiev
Tue Mar 08 2022·2 min read
Photo by Lenart Lipovšek
To sum a property in an array of objects in TypeScript:
reduce()
method to iterate over the array.const arr = [ { id: 1, salary: 25 }, { id: 2, salary: 25 }, { id: 3, salary: 50 }, ]; const result = arr.reduce((accumulator, obj) => { return accumulator + obj.salary; }, 0); console.log(result); // 👉️ 100
The function we passed to the Array.reduce method gets invoked with each element (object) in the array.
accumulator
parameter gets an initial value of 0
, because that's what we supplied as the second parameter to the reduce
method.For each object in the array, we increment the accumulator
by the salary
value in the object.
The reduce
method returns the sum of the salary
values of all objects in the
array.
You might also see examples that explicitly set the accumulator
and return
type of the reduce()
method.
const arr = [ { id: 1, salary: 25 }, { id: 2, salary: 25 }, { id: 3, salary: 50 }, ]; // 👇️ using <number> generic to set return type const result = arr.reduce<number>((accumulator, obj) => { return accumulator + obj.salary; }, 0); console.log(result); // 👉️ 100
The example above uses a
generic
to explicitly set the type for the accumulator
variable and the return type of
the reduce()
method.
An alternative and perhaps simpler approach is to use the forEach
method.
To sum a property in an array of objects:
sum
variable, using the let
keyword and set it to 0
.forEach()
method to iterate over the array.sum
variable with the value of the object.const arr = [ { id: 1, salary: 25 }, { id: 2, salary: 25 }, { id: 3, salary: 50 }, ]; let sum = 0; arr.forEach((obj) => { sum += obj.salary; }); console.log(sum); // 👉️ 100
The function we pass to the Array.forEach method gets called with each element in the array.
sum
variable using the let
keyword. We can't reassign variables declared using const
.On each iteration of the loop, we increment the value stored in the sum
variable to get the total amount.
This approach is more readable and intuitive, especially if you're not used to
how the reduce
method works.