Library reference

Add the values in a list

Add every item once. Repeated values still count each time they occur.

Array.reduce

Simple example

Add one, two and three.

Start1 · 2 · 3
Result6
lesson.ts
const values: number[] = [1, 2, 3];
console.log(values.reduce((total, value) => total + value, 0));
Output
6
Advertisements

Everyday examples

Add the three amounts on a receipt.

Start5 · 5 · 8
Result18
lesson.ts
const values: number[] = [5, 5, 8];
console.log(values.reduce((total, value) => total + value, 0));
Output
18

How many passengers boarded at the three stops?

Start2 · 7 · 1
Result10
lesson.ts
const values: number[] = [2, 7, 1];
console.log(values.reduce((total, value) => total + value, 0));
Output
10

How many exercise books arrived in three boxes?

Start10 · 8 · 9
Result27
lesson.ts
const values: number[] = [10, 8, 9];
console.log(values.reduce((total, value) => total + value, 0));
Output
27
Run the example
Terminal
tsc --target ES2020 lesson.ts
node lesson.js
Official documentation