How to Use Array reduce method in JavaScript

  • 7 min read
  • October 29, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

The Array object’s reduce method is an iteration method which, similar to other iteration methods (map(), forEach(), filter() etc.) helps us work through all of the elements of a dataset, performing actions on each one.

Array reduce has two very powerful features:

  1. It always returns a single value.
  2. You get to choose the data type to be returned.

This article will explore both of these features of the reduce method.

First, let’s take a look at a basic reduce() method example. We’ll then compare it with the Syntax for reduce().

Array reduce basic example

Sum an array

The following example uses Array.reduce() to sum the contents of an array of integers:

const q4th = [109369, 115738, 100936];
const sum = q4th.reduce(function (accumulator, monthlySales) {
    return accumulator + monthlySales;
}, 0);
console.log('Total sales for the fourth quarter: $', sum);
// Expected output: Total sales for the fourth quarter: $ 326043

In the above example, const q4th stores the total amount of sales made in various months. The code above demonstrates how an array of three items is reduced to a single value – the total sum of these sales. Let’s explore how this works by looking at the syntax of the reduce() method.

Syntax

The syntax for array reduce may seem a little complicated at first glance, but it is actually fairly straightforward:

Array.reduce(reducer function(accumulator, currentValue, index, array), initialValue)

Array reduce() is comprised of two parts:

  1. A reducer function that takes up to four parameters, and
  2. An initial value.

The reducer function is executed for each item in the array (with one exception – see the section on the intialValue parameter below).

The returned value of the reducer function is stored in the accumulator parameter, which is the first parameter for the function. This value is retained and updated during each iteration. The accumulator is essential for calculating the return value of the reduce() operation.

Before going through the details of each element of the reduce() method, let’s compare the syntax definition above with the example code:

const sum = q4th.reduce(function (accumulator, monthlySales) {
    return accumulator + monthlySales;
}, 0);

In the code above, the reducer is an anonymous function (a function defined without a name, only the keyword ‘function’).

The accumulator is provided as the first argument to the reducer function. This is often abbreviated as “acc” – we’ve used the full name above for clarity’s sake.

monthlySales is the currentValue of each iteration – meaning the value of the current item in the array that the reducer function is operating on.

Finally, the initialValue is set to zero (0).

The reduce method execution, broken down into iterations

This execution of the above code block will go through the following iterations, The initial state will be as follows:

  • const sum will remain undefined until the iteration process is completed.
  • The accumulator is initialized with the value 0 (provided in the initialValue parameter)

Let’s walk through the values of each object at each iteration:

First iteration

accumulator = 0; 	currentValue = 109369; 		returnValue = 109369

Second iteration

accumulator = 109369; 	currentValue = 115738; 		returnValue = 225107

Third iteration

accumulator = 225107; 	currentValue = 100936; 		returnValue = 326043

 

The above example demonstrates how reduce() works through an array of values. During the first iteration, the accumulator value is equal to the initial value. For every iteration afterwards, the accumulator value is set to the return value of the reducer function.

When there are no more items in the array, const sum is assigned the final value of the accumulator parameter:

const sum = 326043

Parameters

The parameters to Array.reduce() are as follows:

  • reducer callback function

A function to be executed on each item of the array.

    • accumulator: accumulates the return value of the reducer function.
    • currentValue: the value of the current item being processed
    • index (optional): the index of the current item being processed.
    • array (optional): the array that reduce() is operating on.
  • initialValue (optional): the value to use as the first argument for the first call of the reducer function.

When omitted, the value of the first item in the array is used as the initial value of the accumulator. In such a case, the reducer callback function is not executed for the first item. The index count begins at one, instead of the usual zero.

When omitting an initialValue, the result would be the same as if the first iteration was skipped.

Controlling the return value data type

In the above example, the array being operated on was an array of numbers describing sales totals. Each item has a value of type Number and, naturally, the return value (326043) is of the same type.

This is not required – we can set the initialValue to a data type that differs from the array entirely if we wish to do so.

Using the reduce() method to get an Object from an Array

For example, let’s say we have an array of Strings describing differently-colored balls kept together in a bag.

const balls = ['green', 'blue', 'pink', 'yellow', 'blue', 'yellow', 'green'];
var ballsMap = balls.reduce((acc, ball) => {
    if (acc[ball] >= 1) acc[ball]++;
    else acc[ball] = 1;
    return acc;
}, {});
console.log(ballsMap);
// Expected output: {green: 2, blue: 2, pink: 1, yellow: 2}

In the example above, const balls stores the colors of the balls in the bag.

The initial value provided is an empty Object.

Instead of an anonymous function, an arrow function is provided for the reducer.

The first iteration sets the first key of the return object to be ‘green’, with the value of 1. It will do the same for the next three colors as well. After the fourth iteration, the ballsMap object will contain {green: 1, blue: 1, pink: 1, yellow: 1}

This occurs as each iteration is hitting the else statement above. The if statement only comes into play when we encounter a color for a second time – in this case, when we see ‘blue’ for the second time. When this occurs, the code updates the value for the ‘blue’ property name to 2, and it will continue to do so for additional cases where a color is repeated.

For more about the if…else statement check out this link.

Using reduce() method to get a String from an Array

Let’s next look at an example that produces a String value from the contents of an Array object:

const cypered = [67, 111, 100, 111, 116, 97];
const deciphered = cypered.reduce((acc, code) => {
    acc += String.fromCharCode(code)
    return acc
}, '');
console.log(deciphered);
// Expected output: Codota

In the above code, const cyphered is an array storing the character codes for different characters.

This example is also using an arrow function to define the reducer callback function.

The Initial value in this example is an empty String. After each iteration, the accumulator is updated to include the character represented by the code at the current location in the array.

Note: The above two examples will not work properly if the initial value is not provided. This is because when the initial value is omitted, the default initial value is the first item in the array, resulting in output that does not match with the desired result.

In both cases the end result of the reduce() operation is a single value – a single Object in the first example, and a single String in the second.

 

Related Articles

JavaScript – How to Use The Array forEach() Method

JavaScript – How to Use if…else Statements

JavaScript – How to Use Asynchronous Functions

Related Posts

How to Change CSS Using JavaScript

How to Change CSS Using JavaScript

Cascading Style Sheets (CSS) is used to design the layout of a webpage. CSS is a set of structured rules describing the layout of elements in

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement

How to use the for…of Statement in JavaScript

How to use the for…of Statement in JavaScript

The for…of statement was introduced in ECMAScript2015 (ES6) and adds a powerful new type of loop to JavaScript. JavaScript offers many different types of loops, each