Array.prototype.reduce()

  • Revision slug: JavaScript/Reference/Global_Objects/Array/Reduce
  • Revision title: Array reduce method
  • Revision id: 45756
  • Created:
  • Creator: rwaldron
  • Is current revision? No
  • Comment one or more formatting changes

Revision Content

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

Method of Array
Implemented in JavaScript 1.8
ECMAScript Edition ECMAScript 5th Edition

Syntax

array.reduce(callback[, initialValue])

Parameters

callback
Function to execute on each value in the array.
initialValue
Object to use as the first argument to the first call of the callback.

Description

reduce executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the array over which iteration is occurring.

The call to the reduce callback would look something like this:

.reduce(function(previousValue, currentValue, index, array){
  // ...
})

The first time the function is called, the previousValue and currentValue can be one of two values. If an initialValue was provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second.

Some example run-throughs of the function would look like this:

[0,1,2,3,4].reduce(function(previousValue, currentValue, index, array){
  return previousValue + currentValue;
});

// First call
previousValue = 0, currentValue = 1, index = 1

// Second call
previousValue = 1, currentValue = 2, index = 2

// Third call
previousValue = 3, currentValue = 3, index = 3

// Fourth call
previousValue = 6, currentValue = 4, index = 4

// array is always the object [0,1,2,3,4] upon which reduce was called

// Return Value: 10

And if you were to provide an initialValue, the result would look like this:

[0,1,2,3,4].reduce(function(previousValue, currentValue, index, array){
  return previousValue + currentValue;
}, 10);

// First call
previousValue = 10, currentValue = 0, index = 0

// Second call
previousValue = 10, currentValue = 1, index = 1

// Third call
previousValue = 11, currentValue = 2, index = 2

// Fourth call
previousValue = 13, currentValue = 3, index = 3

// Fifth call
previousValue = 16, currentValue = 4, index = 4

// array is always the object [0,1,2,3,4] upon which reduce was called

// Return Value: 20

Compatibility

reduce is a recent addition to the ECMA-262 standard; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of reduce in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming Object and TypeError have their original values and that fun.call evaluates to the original value of Function.prototype.call.  {{ var DO_NOT_MODIFY_THE_FOLLOWING_CODE_IN_ANY_WAY = 0; }}

if ( !Array.prototype.reduce ) {

  Array.prototype.reduce = function(callbackFn /*, initialValue */) {
    "use strict";

    var t = Object(this), 
    len = t.length >>> 0;

    // if callbackFn is not a callable function and
    // no value to return if no initial value and an empty array
    if ( typeof callbackFn !== "function" || 
          (len == 0 && arguments.length == 1) ) {
      throw new TypeError();
    }

    var k = 0,
    initialValue = arguments[1],
    accumulator = initialValue;
    

    do {
      if ( k in t ) {
        accumulator = t[ k++ ];
        break;
      }

      // if array contains no values, no initial value to return
      if (++k >= len) {
        throw new TypeError();
      }
    } while( true );

    while( k < len ) {
      if ( k in t ) {
        accumulator = callbackFn.call(null, accumulator, t[k], k, t);
      }
      k++;
    }

    return accumulator;
  };
}

Examples

Example: Sum up all values within an array

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

Example: Flatten an array of arrays

var flattened = [[0,1], [2,3], [4,5]].reduce(function(a,b) {
  return a.concat(b);
});
// flattened is [0, 1, 2, 3, 4, 5]

See Also

{{ languages( { "es": "es/Referencia_de_JavaScript_1.5/Objetos_globales/Array/reduce", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/Array/reduce", "ja": "ja/Core_JavaScript_1.5_Reference/Objects/Array/reduce" } ) }}

Revision Source

<p>Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.</p>
<table class="standard-table"> <thead> <tr> <th class="header" colspan="2">Method of <a href="/en/JavaScript/Reference/Global_Objects/Array" title="en/JavaScript/Reference/Global_Objects/Array"><code>Array</code></a></th> </tr> </thead> <tbody> <tr> <td>Implemented in</td> <td>JavaScript 1.8</td> </tr> <tr> <td>ECMAScript Edition</td> <td>ECMAScript 5th Edition</td> </tr> </tbody>
</table>
<h2 name="Syntax">Syntax</h2>
<p><code><em>array</em>.reduce(<em>callback</em>[, <em>initialValue</em>])</code></p>
<h2 name="Parameters">Parameters</h2>
<dl> <dt><code>callback</code></dt> <dd>Function to execute on each value in the array.</dd> <dt><code>initialValue</code></dt> <dd>Object to use as the first argument to the first call of the <code>callback</code>.</dd>
</dl>
<h2 name="Description">Description</h2>
<p><code>reduce</code> executes the <code>callback</code> function once for each element present in the array, excluding holes in the array, receiving four arguments: the initial value (or value from the previous <code>callback</code> call), the value of the current element, the current index, and the array over which iteration is occurring.</p>
<p>The call to the reduce <code>callback</code> would look something like this:</p>
<pre class="eval">.reduce(function(previousValue, currentValue, index, array){
  // ...
})
</pre>
<p>The first time the function is called, the <code>previousValue</code> and <code>currentValue</code> can be one of two values. If an <code>initialValue</code> was provided in the call to <code>reduce</code>, then <code>previousValue</code> will be equal to <code>initialValue</code> and <code>currentValue</code> will be equal to the first value in the array. If no <code>initialValue</code> was provided, then <code>previousValue</code> will be equal to the first value in the array and <code>currentValue</code> will be equal to the second.</p>
<p>Some example run-throughs of the function would look like this:</p>
<pre class="brush: js">[0,1,2,3,4].reduce(function(previousValue, currentValue, index, array){
  return previousValue + currentValue;
});

// First call
previousValue = 0, currentValue = 1, index = 1

// Second call
previousValue = 1, currentValue = 2, index = 2

// Third call
previousValue = 3, currentValue = 3, index = 3

// Fourth call
previousValue = 6, currentValue = 4, index = 4

// array is always the object [0,1,2,3,4] upon which reduce was called

// Return Value: 10
</pre>
<p>And if you were to provide an <code>initialValue</code>, the result would look like this:</p>
<pre class="brush: js">[0,1,2,3,4].reduce(function(previousValue, currentValue, index, array){
  return previousValue + currentValue;
}, 10);

// First call
previousValue = 10, currentValue = 0, index = 0

// Second call
previousValue = 10, currentValue = 1, index = 1

// Third call
previousValue = 11, currentValue = 2, index = 2

// Fourth call
previousValue = 13, currentValue = 3, index = 3

// Fifth call
previousValue = 16, currentValue = 4, index = 4

// array is always the object [0,1,2,3,4] upon which reduce was called

// Return Value: 20
</pre>
<h2 name="Compatibility">Compatibility</h2>
<p><code>reduce</code> is a recent addition to the ECMA-262 standard; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>reduce</code> in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming <code style="color: inherit; font-weight: inherit; ">Object </code>and <code style="color: inherit; font-weight: inherit; ">TypeError</code> have their original values and that <code style="color: inherit; font-weight: inherit; ">fun.call</code> evaluates to the original value of <code style="color: inherit; font-weight: inherit; "><a href="/en/JavaScript/Reference/Global_Objects/Function/call" rel="internal" style="text-decoration: none; color: rgb(4, 137, 183) !important; cursor: default; ">Function.prototype.call</a></code>.  {{ var DO_NOT_MODIFY_THE_FOLLOWING_CODE_IN_ANY_WAY = 0; }}</p>
<pre class="brush: js">if ( !Array.prototype.reduce ) {

  Array.prototype.reduce = function(callbackFn /*, initialValue */) {
    "use strict";

    var t = Object(this), 
    len = t.length &gt;&gt;&gt; 0;

    // if callbackFn is not a callable function and
    // no value to return if no initial value and an empty array
    if ( typeof callbackFn !== "function" || 
          (len == 0 &amp;&amp; arguments.length == 1) ) {
      throw new TypeError();
    }

    var k = 0,
    initialValue = arguments[1],
    accumulator = initialValue;
    

    do {
      if ( k in t ) {
        accumulator = t[ k++ ];
        break;
      }

      // if array contains no values, no initial value to return
      if (++k &gt;= len) {
        throw new TypeError();
      }
    } while( true );

    while( k &lt; len ) {
      if ( k in t ) {
        accumulator = callbackFn.call(null, accumulator, t[k], k, t);
      }
      k++;
    }

    return accumulator;
  };
}

</pre>
<h2 name="Examples">Examples</h2>
<h3 name="Example:_Sum_up_all_values_within_an_array">Example: Sum up all values within an array</h3>
<pre class="brush: js">var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });
// total == 6
</pre>
<h3 name="Example:_Flatten_an_array_of_arrays">Example: Flatten an array of arrays</h3>
<pre class="brush: js">var flattened = [[0,1], [2,3], [4,5]].reduce(function(a,b) {
  return a.concat(b);
});
// flattened is [0, 1, 2, 3, 4, 5]
</pre>
<h2 name="See_Also">See Also</h2>
<ul> <li><a href="/en/JavaScript/Reference/Global_Objects/Array/ReduceRight" title="en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight">reduceRight</a></li>
</ul>
<p>{{ languages( { "es": "es/Referencia_de_JavaScript_1.5/Objetos_globales/Array/reduce", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/Array/reduce", "ja": "ja/Core_JavaScript_1.5_Reference/Objects/Array/reduce" } ) }}</p>
Revert to this revision