Using reduce in JavaScript

The reduce
function is a powerful tool for processing arrays in JavaScript and TypeScript. It allows you to iterate over an array and accumulate a single value from the elements. Let's explore how it works with some examples.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 15
In this example, reduce
takes two arguments: a callback function and an initial value (0 in this case). The callback function takes two parameters: accumulator
(which starts at 0) and currentValue
(each number in the array). The callback function's return value is assigned to the accumulator
for the next iteration, building up the final sum.
interface Person {
name: string;
age: number;
}
const people: Person[] = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 35 },
];
const totalAge = people.reduce((acc, person) => acc + person.age, 0);
console.log(totalAge); // Output: 90
Here, we're using reduce
to calculate the total age of all people in the array. The accumulator
starts at 0 and each person's age is added to it in each iteration.
const words = ['hello', 'world', 'typescript'];
const concatenatedString = words.reduce((acc, word) => acc + ' ' + word, '');
console.log(concatenatedString); // Output: 'hello world typescript'
This shows how reduce
can be used to concatenate strings. The initial value is an empty string, and each word is appended to it during the iterations.
Subscribe to my newsletter
Read articles from Hossein Margani directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
