How to use the JavaScript Array.prototype.reduce() - JavaScript Reduce Explained with Examples

How to use the JavaScript Array.prototype.reduce() - JavaScript Reduce Explained with Examples
0

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

Syntax

arr.reduce(callback[, initialValue])

Parameters

  • callback Function to execute on each value in the array, taking four arguments:

    • previousValue The value previously returned in the last invocation of the callback, or initialValue, if supplied. (See below.)

    • currentValue The current element being processed in the array.

    • currentIndex The index of the current element being processed in the array.

    • array The array reduce was called upon.

  • initialValue Optional. Value to use as the first argument to the first call of the callback.

MDN link | MSDN link

Returns

The accumulated result from the last call to the callback function.

Description

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

Remarks

If an initialValue is provided, the reduce method calls the callback function one time for each element present in the array, in ascending index order. If an initialValue is not provided, the reduce method calls the callback function on each element, starting with the second element.

The return value of the callback function is provided as the previousValue argument on the next call to the callback function. The return value of the last call to the callback function is the return value of the reduce method.

The callback function is not called for missing elements of the array.

Examples

var total = [0, 1, 2, 3].reduce(function(a, b) {
  return a + b;
});
// total == 6

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
  return a.concat(b);
}, []);
// flattened is [0, 1, 2, 3, 4, 5]
// Define the callback function.
function appendCurrent (previousValue, currentValue) {
    return previousValue + "::" + currentValue;
    }

// Create an array.
var elements = ["abc", "def", 123, 456];

// Call the reduce method, which calls the callback function
// for each array element.
var result = elements.reduce(appendCurrent);

document.write(result);

// Output:
//  abc::def::123::456

Array.prototype.reduce

The reduce() method reduces an array of values down to just one value.

The single value that is returned can be of any type.

Example 1

Transform an array of integers into the sum of all integers in the array.

    var numbers = [1,2,3]; 
    var sum = numbers.reduce(function(total, current){
        return total + current;
    });
    console.log(sum); 

This will output 6 to the console.

Description

The reduce() method has been called the Swiss Army knife, or multi-tool, of array transformation methods. Others, such as map() and filter() , provide more specific transformations, whereas reduce() can be used to transform arrays into any output you desire.

Syntax

    arr.reduce(callback[, initialValue])
  • The callback argument is a function that will be called once for every item in the array. This function takes four arguments, but often only the first two are used.
    • accumulator - the returned value of the previous iteration
    • currentValue - the current item in the array
    • index - the index of the current item
    • array - the original array on which reduce was called
  • The initialValue argument is optional. If provided, it will be used as the initial accumulator value in the first call to the callback function (see Example 2 below). If initialValue is not provided, the iteration will start at the second element in the array (at index 1), with accumulator equal to the first element in the array and currentValue equal to the second element.

Example 2

Transform an array of strings into a single object that shows how many times each string appears in the array.

Notice this call to reduce passes an empty object {} as the initialValue parameter. This will be used as the initial value of the accumulator (the first argument) passed to the callback function.

var pets = ['dog', 'chicken', 'cat', 'dog', 'chicken', 'chicken', 'rabbit'];

var petCounts = pets.reduce(function(obj, pet){
    if (!obj[pet]) {
        // if the pet doesn't yet exist as a property of the accumulator object, 
        //   add it as a property and set its count to 1
        obj[pet] = 1;
    } else {
        // pet exists, so increment its count
        obj[pet]++;
    }
    return obj; // return the modified object to be used as accumulator in the next iteration
}, {}); // initialize the accumulator as an empty object

console.log(petCounts); 

Output:

 { 
    dog: 2, 
    chicken: 3, 
    cat: 1, 
    rabbit: 1 
 }
8 Likes