JavaScript Array reduce & reduceRight: Reducing an Array Into a Value

Summary: in this tutorial, you will learn how to use the JavaScript Array reduce() and reduceRight() methods to reduce an array to a value.

Introduction to the JavaScript Array reduce() method

Suppose that you have an array of numbers, like this:

let numbers = [1, 2, 3];Code language: JavaScript (javascript)

and you want to calculate the total of elements of the array.

Typically, you use a for loop to iterate over the elements and add them up as shown in the following example:

let numbers = [1, 2, 3];

let sum = 0;
for (let i = 0; i < numbers.length; i++) {
    sum += numbers[i];
}

console.log(sum);Code language: JavaScript (javascript)

Output:

6

The script is simple and straightforward:

  • First, declare an array of three numbers 1, 2 and 3.
  • Second, declare the sum variable and set its value to zero.
  • Third, in the for loop, add up the elements of the numbers array to the sum variable. After the loop, the value of the sum variable is 6.

What we have done was to reduce an array into a value.

The Array.prototype allows you to reduce an array to a single value using the reduce() method like this:

let numbers = [1, 2, 3];
let sum = numbers.reduce(function (previousValue, currentValue) {
    return previousValue + currentValue;
});

console.log(sum);Code language: JavaScript (javascript)

It’s pretty simple, isn’t it?

Let’s take a look at the reduce() method in detail.

JavaScript Array reduce() method in detail

The following illustrates the syntax of the reduce() method:

array.reduce(callbackFn [, initialValue])Code language: CSS (css)

The reduce() method takes two arguments:

  • A callback function callbackFn. The function is often referred to as a reducer.
  • An optional initial value.

The reduce() method calls the callbackFn() function for every element in the array.

The reducer() function returns a value that results from executing the callbackFn to completion over the entire array.

1) The callbackFn() function argument

The callbackFn function has the following syntax:

function callbackFn(previousValue, currentValue, currentIndex, array) { /**/}Code language: PHP (php)

The callbackFn function takes four arguments:

previousValue

The value returned from the previous call of the callbackFn function. On the first call, the initialValue is the previousValue if you pass the initialValue. Otherwise, its value is the array[0].

currentValue

The value of the current array element. On the first call, it is array[0] if you pas the initialValue or array[1] otherwise.

currentIndex

The index of the currentValue in the array. On the first call, it’s 0 if you pass the initialValue or 1 otherwise.

array

The array to loop through.

2) The initialValue argument

The initialValue argument is optional.

If you specify the initialValue, the callbackFn function will initialize the previousValue to the initialValue and currentValue to the first array’s element on the first call.

If you don’t specify the initialValue, the the callbackFn function will initialize the previousValue to the first array’s element (array[0]) in the array and the currentValue to the second array’s element (array[1]).

The following table illustrates the logic when the reduce() method executes the callbackFn() function for the first time according to the initialValue argument:

initialValue previousValue currentValue
passedinitialValue array[0]
not passedarray[0] array[1]

The following example shows the progress of the reduce() function with an initialValue as 100:

let numbers = [1, 2, 3];

function getOrdinalSuffix(i) {
  let j = i % 10, k = i % 100;
  if (j == 1 && k != 11) return i + 'st';
  if (j == 2 && k != 12) return i + 'nd';  
  if (j == 3 && k != 13) return i + 'rd';
  return i + 'th';
}

let call = 1;
let sum = numbers.reduce(function (previousValue, currentValue, currentIndex, array) {
    let result = previousValue + currentValue;

    // show the 1st call, 2nd call, etc.
    console.log(`${getOrdinalSuffix(call)} call`);
    call++;

    // show the immediate values
    console.table({ previousValue, currentValue, currentIndex, result });

    return result;
},100);

console.log(`Result: ${sum}`);Code language: JavaScript (javascript)

Output:

1st call
┌───────────────┬────────┐
│    (index)    │ Values │
├───────────────┼────────┤
│ previousValue │  100   │
│ currentValue  │   1    │
│ currentIndex  │   0    │
│    result     │  101   │
└───────────────┴────────┘
2nd call
┌───────────────┬────────┐
│    (index)    │ Values │
├───────────────┼────────┤
│ previousValue │  101   │
│ currentValue  │   2    │
│ currentIndex  │   1    │
│    result     │  103   │
└───────────────┴────────┘
3rd call
┌───────────────┬────────┐
│    (index)    │ Values │
├───────────────┼────────┤
│ previousValue │  103   │
│ currentValue  │   3    │
│ currentIndex  │   2    │
│    result     │  106   │
└───────────────┴────────┘
Result: 106Code language: plaintext (plaintext)

And the following illustrates the reduce() method without the initialValue argument:

1st call
┌───────────────┬────────┐
│    (index)    │ Values │
├───────────────┼────────┤
│ previousValue │   1    │
│ currentValue  │   2    │
│ currentIndex  │   1    │
│    result     │   3    │
└───────────────┴────────┘
2nd call
┌───────────────┬────────┐
│    (index)    │ Values │
├───────────────┼────────┤
│ previousValue │   3    │
│ currentValue  │   3    │
│ currentIndex  │   2    │
│    result     │   6    │
└───────────────┴────────┘
Result: 6Code language: plaintext (plaintext)

More JavaScript Array reduce() examples

Suppose that you have the following shoppingCart array of product objects:

let shoppingCart = [
  {
    product: 'phone',
    qty: 1,
    price: 500,
  },
  {
    product: 'Screen Protector',
    qty: 1,
    price: 10,
  },
  {
    product: 'Memory Card',
    qty: 2,
    price: 20,
  },
];Code language: JavaScript (javascript)

To calculate the total amount of the products in the shopping cart, you can use the reduce() method, like this:

let total = shoppingCart.reduce(function (previousValue, currentValue) {
  return previousValue + currentValue.qty * currentValue.price;
}, 0);Code language: JavaScript (javascript)

Output:

550

Notice that in this example, we passed in the initialValue argument to the reduce() method.

If we didn’t do so, the reduce() method would take the first element of the shoppingCart array, which is an object, as an initial value and perform the calculation on this object. Hence, it would cause an incorrect result.

JavaScript Array reduceRight() method

The reduceRight() method works in the same way as the reduce() method, but in the opposite direction.

The reduce() method starts at the first element and travels toward the last, whereas the reduceRight() method starts at the last element and travels backward the first.

See the following example:

let numbers = [1, 2, 3];

let sum = numbers.reduceRight(function (previousValue, currentValue) {
  console.log({ previousValue, currentValue });
  return previousValue + currentValue;
});

console.log(`Result:${sum}`);Code language: JavaScript (javascript)

Output

{ previousValue: 3, currentValue: 2 }
{ previousValue: 5, currentValue: 1 }
Result:6Code language: CSS (css)

The following picture illustrates the difference between the reduce() and reduceRight() methods:

javascript array reduce

In this tutorial, you have learned how to use the JavaScript array reduce() and reduceRight() methods to reduce an array into a value.

Was this tutorial helpful ?