Sum numbers in array of objects with Typescript
In the old days a simple for loop would be enough. It still is, but way more code then needed when working with arrays.
When working with reduce
we can create a sum for every item. In the example we have a TimeEntry
interface with multiple attributes. We only care about numberOfHours
. For every entry the callback is called, the second parameter is the default value:
interface TimeEntry {
approvedAt?: string;
rejectedAt?: string;
numberOfHours: number;
}
...
get numberOfUnhandledHours() {
return this.timeEntries
.reduce((sum: number, b: TimeEntry) => b.numberOfHours, 0);
}
The nice effect here is that we can chain other methods like filter methods to it:
get numberOfUnhandledHours() {
return this.timeEntries
.filter((timeEntry: TimeEntry) => !timeEntry.approvedAt && !timeEntry.rejectedAt)
.reduce((sum: number, b: TimeEntry) => sum + b.numberOfHours, 0);
}
This way we can add more complexity without have one if after another within a nested loop.