EN
TypeScript - sum / subtract numbers in array with reduce()
3
points
In this article, we would like to show you how to sum and subtract numbers with reduce() method in TypeScript.
1. Sum example
In the below example, we execute sum function provided to the reduce() method that sums all the numbers in the array.
const numbers: number[] = [1, 2, 3];
const sum = numbers.reduce((accumulator: number, input: number): number => accumulator + input);
console.log(sum); // 6
Output:
6
2. Subtract example
In the below example, we execute subtract function provided to the reduce() method that subtracts all the numbers in the array from the accumulator (first item in the array).
const numbers: number[] = [10, 1, 2];
const subtract = numbers.reduce((accumulator: number, input: number): number => accumulator - input);
console.log(subtract); // 7
Output:
7