JavaScript Array Operators: REDUCE

JavaScript Sep 23, 2021

Hi and welcome to the second episode of the JavaScript Operators series. Today is all about the REDUCE operator, who can be applied on arrays. The reduce() method takes two arguments and returns one result for the whole array. It iterates over all values beginning from the left and takes the current value and the result from the previous run.

The far best way to understand the reducer is to calculate the sum of an array full of integer values. The following example takes 10 and adds 20, then it takes 30 and adds 30, then it takes 60 and add 40 and finally, it takes 100 and adds 50 to then return 150. If you do not provide a initialValue for the first run, previousValue will be set to the first element.

const numbers = [10, 20, 30, 40, 50];
const result = numbers.reduce((previousValue, currentValue) => previousValue + currentValue);

console.log(result);
// 150

However, the reduce()method does work with any object, and it is not limited to numbers. You can concatenate strings or work with complex objects as well.

const texts = ["Hello", "my", "friend", "!"];
const result = texts.reduce((previousValue, currentValue) => previousValue + " " + currentValue);

console.log(result);
// Hello my friend !

Parameters

The reduce operator supports a callback function with multiple parameters.

reduce(function callbackFn(previousValue, currentValue, currentIndex, array)

callbackFn
The callback function takes up to four arguments.

  • previousValue (the result of the previous callback function).
  • currentValue (the value of the current item in the array)
  • currentIndex [optional] (the value of the current array index)
  • array [optional] (optional: the array to traverse)

initialValue [optional]
You can set the value of the first iteration, otherwise the first previousValue is not initialized.

Find out more here.

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.