Array.prototype.reduce()

  • Revision slug: JavaScript/Reference/Global_Objects/Array/Reduce
  • Revision title: Array reduce method
  • Revision id: 364115
  • Created:
  • Creator: evgeniypavlyuk
  • Is current revision? No
  • Comment Ensures that array has index as its own property. This covers cases if an array has reserved items (for instance, new Array(1), or var a = [1, 2, 3]; delete a[1]).

Revision Content

Summary

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, 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.
index
The index of the current element being processed in the array.
array
The array reduce was called upon.
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 first time the callback is called, previousValue and currentValue can be one of two values. If initialValue is 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.

Suppose the following use of reduce occurred:

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

The callback would be invoked four times, with the arguments and return values in each call being as follows:

  previousValue currentValue index array return value
first call 0 1 1 [0,1,2,3,4] 1
second call 1 2 2 [0,1,2,3,4] 3
third call 3 3 3 [0,1,2,3,4] 6
fourth call 6 4 4 [0,1,2,3,4] 10

The value returned by reduce would be that of the last callback invocation (10).

If you were to provide an initial value as the second argument to reduce, the result would look like this:

[0,1,2,3,4].reduce(function(previousValue, currentValue, index, array){
  return previousValue + currentValue;
}, 10);
  previousValue currentValue index array return value
first call 10 0 0 [0,1,2,3,4] 10
second call 10 1 1 [0,1,2,3,4] 11
third call 11 2 2 [0,1,2,3,4] 13
fourth call 13 3 3 [0,1,2,3,4] 16
fifth call 16 4 4 [0,1,2,3,4] 20

The value returned by reduce this time would be, of course, 20.

Compatibility

Array.prototype.reduce is an ECMAScript 5 addition; 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.

if ('function' !== typeof Array.prototype.reduce) {
  Array.prototype.reduce = function(callback, opt_initialValue){
    if ('function' !== typeof callback) {
      throw new TypeError(String(callback) + ' is not a function');
    }
    var index = 0, length = this.length >>> 0, value, isValueSet = false;
    if (1 < arguments.length) {
      value = opt_initialValue;
      isValueSet = true;
    }
    for ( ; length > index; ++index) {
      if (!this.hasOwnProperty(index)) continue;
      if (isValueSet) {
        value = callback(value, this[index], index, this);
      } else {
        value = this[index];
        isValueSet = true;
      }
    }
    if (!isValueSet) {
      throw new TypeError('Reduce of empty array with no initial value');
    }
    return value;
  };
}

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]

Browser compatibility

Based on Kangax's compat tables

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{CompatVersionUnknown}} {{CompatGeckoDesktop("1.9")}} 9 10.5 4.0
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}}

See also

Revision Source

<h2 id="Summary">Summary</h2>
<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-US/docs/JavaScript/Reference/Global_Objects/Array" title="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 id="Syntax">Syntax</h2>
<pre class="syntaxbox">
<code><var style="font-style: italic;">array</var>.reduce(<var style="font-style: italic;">callback</var><span style="font-style: italic;">[</span>, <var style="font-style: italic;">initialValue</var><span style="font-style: italic;">]</span>)</code></pre>
<h3 id="Parameters">Parameters</h3>
<dl>
  <dt>
    <code>callback</code></dt>
  <dd>
    Function to execute on each value in the array, taking four arguments:
    <dl>
      <dt>
        <code>previousValue</code></dt>
      <dd>
        The value previously returned in the last invocation of the callback, or <code>initialValue</code>, if supplied. (See below.)</dd>
      <dt>
        <code>currentValue</code></dt>
      <dd>
        The current element being processed in the array.</dd>
      <dt>
        <code>index</code></dt>
      <dd>
        The index of the current element being processed in the array.</dd>
      <dt>
        <code>array</code></dt>
      <dd>
        The array <code>reduce</code> was called upon.</dd>
    </dl>
  </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 id="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 first time the callback is called, <code>previousValue</code> and <code>currentValue</code> can be one of two values. If <code>initialValue</code> is 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>Suppose the following use of <code>reduce</code> occurred:</p>
<pre class="brush:js">
[0,1,2,3,4].reduce(function(previousValue, currentValue, index, array){
  return previousValue + currentValue;
});
</pre>
<p>The callback would be invoked four times, with the arguments and return values in each call being as follows:</p>
<table border="1" cellpadding="1" cellspacing="1" style="width: 100%; table-layout: fixed;">
  <thead>
    <tr>
      <th scope="col">&nbsp;</th>
      <th scope="col"><code>previousValue</code></th>
      <th scope="col"><code>currentValue</code></th>
      <th scope="col"><code>index</code></th>
      <th scope="col"><code>array</code></th>
      <th scope="col">return value</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">first call</th>
      <td><code>0</code></td>
      <td><code>1</code></td>
      <td><code>1</code></td>
      <td><code>[0,1,2,3,4]</code></td>
      <td><code>1</code></td>
    </tr>
    <tr>
      <th scope="row">second call</th>
      <td><code>1</code></td>
      <td><code>2</code></td>
      <td><code>2</code></td>
      <td><code>[0,1,2,3,4]</code></td>
      <td><code>3</code></td>
    </tr>
    <tr>
      <th scope="row">third call</th>
      <td><code>3</code></td>
      <td><code>3</code></td>
      <td><code>3</code></td>
      <td><code>[0,1,2,3,4]</code></td>
      <td><code>6</code></td>
    </tr>
    <tr>
      <th scope="row">fourth call</th>
      <td><code>6</code></td>
      <td><code>4</code></td>
      <td><code>4</code></td>
      <td><code>[0,1,2,3,4]</code></td>
      <td><code>10</code></td>
    </tr>
  </tbody>
</table>
<p>The value returned by <code>reduce</code> would be that of the last callback invocation (<code>10</code>).</p>
<p>If you were to provide an initial value as the second argument to <code>reduce</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);
</pre>
<table border="1" cellpadding="1" cellspacing="1" style="width: 100%; table-layout: fixed;">
  <thead>
    <tr>
      <th scope="col">&nbsp;</th>
      <th scope="col"><code>previousValue</code></th>
      <th scope="col"><code>currentValue</code></th>
      <th scope="col"><code>index</code></th>
      <th scope="col"><code>array</code></th>
      <th scope="col">return value</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">first call</th>
      <td><code>10</code></td>
      <td><code>0</code></td>
      <td><code>0</code></td>
      <td><code>[0,1,2,3,4]</code></td>
      <td><code>10</code></td>
    </tr>
    <tr>
      <th scope="row">second call</th>
      <td><code>10</code></td>
      <td><code>1</code></td>
      <td><code>1</code></td>
      <td><code>[0,1,2,3,4]</code></td>
      <td><code>11</code></td>
    </tr>
    <tr>
      <th scope="row">third call</th>
      <td><code>11</code></td>
      <td><code>2</code></td>
      <td><code>2</code></td>
      <td><code>[0,1,2,3,4]</code></td>
      <td><code>13</code></td>
    </tr>
    <tr>
      <th scope="row">fourth call</th>
      <td><code>13</code></td>
      <td><code>3</code></td>
      <td><code>3</code></td>
      <td><code>[0,1,2,3,4]</code></td>
      <td><code>16</code></td>
    </tr>
    <tr>
      <th scope="row">fifth call</th>
      <td><code>16</code></td>
      <td><code>4</code></td>
      <td><code>4</code></td>
      <td><code>[0,1,2,3,4]</code></td>
      <td><code>20</code></td>
    </tr>
  </tbody>
</table>
<p>The value returned by <code>reduce</code> this time would be, of course, <code>20</code>.</p>
<h2 id="Compatibility">Compatibility</h2>
<p><code>Array.prototype.reduce</code> is an ECMAScript 5 addition; 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.</p>
<pre class="brush:js">
if ('function' !== typeof Array.prototype.reduce) {
  Array.prototype.reduce = function(callback, opt_initialValue){
    if ('function' !== typeof callback) {
      throw new TypeError(String(callback) + ' is not a function');
    }
    var index = 0, length = this.length &gt;&gt;&gt; 0, value, isValueSet = false;
    if (1 &lt; arguments.length) {
      value = opt_initialValue;
      isValueSet = true;
    }
    for ( ; length &gt; index; ++index) {
      if (!this.hasOwnProperty(index)) continue;
      if (isValueSet) {
        value = callback(value, this[index], index, this);
      } else {
        value = this[index];
        isValueSet = true;
      }
    }
    if (!isValueSet) {
      throw new TypeError('Reduce of empty array with no initial value');
    }
    return value;
  };
}
</pre>
<h2 id="Examples">Examples</h2>
<h3 id="Example.3A_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 id="Example.3A_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 id="Browser_compatibility">Browser compatibility</h2>
<p>Based on <a href="http://kangax.github.com/es5-compat-table/">Kangax's compat tables</a></p>
<div>
  {{CompatibilityTable}}</div>
<div id="compat-desktop">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Chrome</th>
        <th>Firefox (Gecko)</th>
        <th>Internet Explorer</th>
        <th>Opera</th>
        <th>Safari</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>{{CompatVersionUnknown}}</td>
        <td>{{CompatGeckoDesktop("1.9")}}</td>
        <td>9</td>
        <td>10.5</td>
        <td>4.0</td>
      </tr>
    </tbody>
  </table>
</div>
<div id="compat-mobile">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Android</th>
        <th>Chrome for Android</th>
        <th>Firefox Mobile (Gecko)</th>
        <th>IE Mobile</th>
        <th>Opera Mobile</th>
        <th>Safari Mobile</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>{{CompatUnknown}}</td>
        <td>{{CompatUnknown}}</td>
        <td>{{CompatUnknown}}</td>
        <td>{{CompatUnknown}}</td>
        <td>{{CompatUnknown}}</td>
        <td>{{CompatUnknown}}</td>
      </tr>
    </tbody>
  </table>
</div>
<h2 id="See_also">See also</h2>
<ul>
  <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/ReduceRight" title="JavaScript/Reference/Objects/Array/reduceRight">reduceRight</a></li>
</ul>
<!-- languages({ "fr": "fr/docs/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/Array/reduce" }) -->
Revert to this revision