0
0
Javascriptprogramming~5 mins

Reduce method in Javascript

Choose your learning style9 modes available
Introduction

The reduce method helps you combine all items in a list into one value. It makes adding, multiplying, or merging easy.

When you want to add all numbers in an array to get a total.
When you want to find the biggest or smallest number in a list.
When you want to turn a list of words into one sentence.
When you want to count how many times each item appears in a list.
Syntax
Javascript
array.reduce((accumulator, currentValue) => {
  // combine accumulator and currentValue
  return newAccumulator;
}, initialValue);

accumulator holds the combined result so far.

currentValue is the current item from the array.

Examples
Adds all numbers starting from 0.
Javascript
const sum = [1, 2, 3].reduce((acc, val) => acc + val, 0);
Multiplies all numbers starting from 1.
Javascript
const product = [2, 3, 4].reduce((acc, val) => acc * val, 1);
Joins words into a sentence starting with an empty string.
Javascript
const sentence = ['Hello', 'world'].reduce((acc, val) => acc + ' ' + val, '').trim();
Sample Program

This program adds all numbers in the array and prints the total.

Javascript
const numbers = [5, 10, 15];
const total = numbers.reduce((acc, val) => acc + val, 0);
console.log('Total:', total);
OutputSuccess
Important Notes

If you skip the initialValue, reduce uses the first array item as the start.

Reduce works on arrays only.

Summary

Reduce combines array items into one value.

It uses a function with an accumulator and current value.

You can use it to add, multiply, join, or count items.