Learning JavaScript Array.Reduce() Method

Note: This post is work-in-progress learning-note and still in active development and updated regularly.

In the previous posts, Understanding JavaScript Arrays  and Learning JavaScript Array Methods were in detail. Because JS array.reduce() method is more complex and an important method, in this learning-post, we will discuss its basic syntax, how it works and explain with some examples.

Array.Reduce() Method

The array.reduce() method performs callback function once on each array elements (from left to right) reducing into a single value.

Basic Syntax
//without initial value
let reducer = arr.reduce(callback);
//callback function 
let callbackName = function(accu, curVal, cumInd, arr) {
  return accu + curr;
 });

//Arrow function syntax
let reducer = function(accu, curVal, cumInd, arr) => accu + curr;

//with intialValue (optional)
let reducer = arr.reduce(callback, initValue);
//callback function
let callbackName = function(accu, curVal, cumInd, arr) {
  return accu + curr;
 }, iniValue);

//Arrow function syntax
let reducer = function(accu, curVal, cumInd, arr) => accu + curr, iniValue;

The array.reduce() method accepts two arguments: callback function (line 2) and an optional Initial Value (line 12). On MDN these

  • reducer : the single returned value by the reduce() call back function
  • callback : Function to execute on each element in the array, taking four arguments
  • initialValue : Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used.

The callback function (lines 4-6) accepts four parameters:

  • Accumuator : The accumulator accumulates the callback’s return values; it is the accumulated value previously returned in the last invocation of the callback
  • Current Value : The current element being processed in the array.
  • CurrentIndex : the index of the current element being processed in the array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
  • Array : The array reduce() was called upon (i.e. original array).

To find the single reducer value (it could be named as sum or total) each iteration will add currentValue to accumulator value and return it. The returned value will be new accumulator and this process continues until the end of array. Once all the array elements are completed it will return as a single value assigned as reducer.

How reduce() works

Lets examine with a simple example (below) how reduce() method works:

//initialize numbers array
let num = [ 0, 1, 2, 3, 4 ];
//
let sum = num.reduce(function (accum, curValue) {
  return accum + curValue;
});
//OUTPUT
console.log(sum); // => 10

The callback function is invoked four times with the arguments as shown below:

callback accum curValue curIndex array sum
First Call 0 1 1 [0, 1, 2, 3, 4] 1
2nd Call 1 2 2 [0, 1, 2, 3, 4] 3
3rd Call 3 3 3 [0, 1, 2, 3, 4] 6
4th Call 6 4 4 [0, 1, 2, 3, 4] 10

In the first call, accumulator is the initial value (first argument) which is 0, and current value, which is first array) is 1 and its return value (0 + 1) is 1. In the next call, the return of the previous call becomes the first argument (accumulator) and so on. For the 2nd call, its initial value of accumulator is 1, its current value (second element) is 2 so 1 + 2 = 3, its return value is 3. In the last (4th) run, initial value for accumulator is 6 and its current value is 4, which is added and returns final value as 10.

Some Use Case Examples

The following use case examples are adopted from Josh Pitzalis‘s article How JavaScript’s Reduce method works, when to use it, and some of the cool things it can do.

Finding an Average

The Array.reduce() method can be used to find an average by dividing the total value with the length of the array and returning a final value.

//initialize number array
const num = [10, 15, 20, 25, 50];
// Initialize reduce method with arrow function
const average = num.reduce((total, amount, index, array) => {
  total += amount;
  if( index === array.length-1) { 
    return total/array.length;
  }else { 
    return total;
  }
});
//access average value
console.log(average); // OUTPUT => 24

In the example above, the index argument (line 4) is used in if..else loop to iterate over the array and returning itself in the last argument.

Creating A Tally

The following example, adapted from the MDN Reference Document, is used to count instances values (or tally) of each item in a collection of an array.

// initialize cars array
let cars = ['Toyota', 'Ford', 'Honda', 'Toyota', 'BMW'];
//initialize CarCounts with reduce method
var carCounts = cars.reduce(function (allCars, car) { 
  if (car in allCars) {
    allCars[car]++;
  }
  else {
    allCars[car] = 1;
  }
  return allCars;
}, {});

//re-writing carCounts using arrow function syntax
const carCounts = cars.reduce( (allCars, car) => {
  allCars[car] = (allCars[car] || 0) + 1 ;
  return allCars;
} , {})

//Access carCounts value
carCounts; //OUTPUT => {Toyota: 2, Ford: 1, Honda: 1, BMW: 1}

In the example above, array.reduce() is used to tally cars (or count occurrence of each car) using a basic (lines: 4-12) or an arrow function (14-18) which is assigned to a carCounts variable. In this case, the initial value must be empty {} object (lines: 12, 18).

Flattening an Array

The Array.reduce() can also be used to flatten nested arrays into a single array.

// initialize car arrays
let carArrays = [["Camry", "Corolla"], ["Fusion"], ["Civic", "Hybrid"]];
//initilize allVehicles using reduce method
let allVehicles = carArrays.reduce(function(accum, curVal) {
    return accum.concat(curVal);
   },
  [] ); //initial value an empty array
// access allVehicles
allVehicles; //OUTPUT => ["Camry", "Corolla", "Fusion", "Civic", "Hybrid"] 

//re-writing with ES6 Arrow Function syntax 
let allVehicles = carArrays.reduce(
  ( accum, curVal ) => accum.concat(curVal),
  [] // initial value an empty array
);
// access allVehicles
allVehicles; //OUTPUT =>["Camry", "Corolla", "Fusion", "Civic", "Hybrid"]

In the example above, carArrays is initialized with three nested arrays with car names as array items (line 2). Using Array.reduce() method, the three arrays were combined into a single array allVehicles by first, setting initial value as empty (lines: 7, 14) and then concatenating current value curVal to the total value accum (lines: 5, 13).

Tip: Additional use case examples of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce" target="_blank" rel="noopener">Array.reduce()</a> are described on the Mozilla Developer Network.

Wrapping Up

In previous learning-note post Learning JavaScript Array Methods, different built-in array methods were discussed. Because the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce" target="_blank" rel="noopener">Array.reduce()</a> method is an important JS methods is used in performing various task, such as flattening arrays, tallying array items etc, it was discussed separately. In this posts basic array.reduce() method syntax, how it works including its parameters are discussed.

Related Post : Learning JavaScript Array Methods

Useful Resources & Links

While preparing this post, I have referred the following references extensively. Visit original link for additional information.