Revision 496049 of Array.prototype.filter()

  • Revision slug: Web/JavaScript/Reference/Global_Objects/Array/filter
  • Revision title: Array filter method
  • Revision id: 496049
  • Created:
  • Creator: patrickdw
  • Is current revision? No
  • Comment Too many people are breaking these compatibility patches. Rolling back to older version.

Revision Content

Summary

Creates a new array with all elements that pass the test implemented by the provided function.

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

Syntax

array.filter(callback[, thisObject])

Parameters

callback
Function to test each element of the array.
thisObject
Object to use as this when executing callback.

Description

filter calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a true value. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

callback is invoked with three arguments:

  1. the value of the element
  2. the index of the element
  3. the Array object being traversed

If a thisObject parameter is provided to filter, it will be used as the this for each invocation of the callback. If it is not provided, or is null, the global object associated with callback is used instead.

filter does not mutate the array on which it is called.

The range of elements processed by filter is set before the first invocation of callback. Elements which are appended to the array after the call to filter begins will not be visited by callback. If existing elements of the array are changed, or deleted, their value as passed to callback will be the value at the time filter visits them; elements that are deleted are not visited.

Compatibility

filter is a JavaScript extension 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 filter in ECMA-262 implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming that fn.call evaluates to the original value of Function.prototype.call, and that Array.prototype.push has its original value.

// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.com/#x15.4.4.18
if ( !Array.prototype.forEach ) {

  Array.prototype.forEach = function( callback, thisArg ) {

    var T, k;

    if ( this == null ) {
      throw new TypeError( " this is null or not defined" );
    }

    // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0; // Hack to convert O.length to a UInt32

    // 4. If IsCallable(callback) is false, throw a TypeError exception.
    // See: http://es5.github.com/#x9.11
    if ( {}.toString.call(callback) != "[object Function]" ) {
      throw new TypeError( callback + " is not a function" );
    }

    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    if ( arguments.length > 1 ) {
      T = thisArg;
    }

    // 6. Let k be 0
    k = 0;

    // 7. Repeat, while k < len
    while( k < len ) {

      var kValue;

      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      if ( k in O ) {

        // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
        kValue = O[ k ];

        // ii. Call the Call internal method of callback with T as the this value and
        // argument list containing kValue, k, and O.
        callback.call( T, kValue, k, O );
      }
      // d. Increase k by 1.
      k++;
    }
    // 8. return undefined
  };
}

Examples

Example: Filtering out all small values

The following example uses filter to create a filtered array that has all elements with values less than 10 removed.

function isBigEnough(element) {
  return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44] 

Browser compatibility

Based on Kangax's compat tables

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} 9 {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }}

 

Revision Source

<h2 id="Summary" name="Summary">Summary</h2>
<p>Creates a new array with all elements that pass the test implemented by the provided function.</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.6</td>
  </tr>
  <tr>
   <td>ECMAScript Edition</td>
   <td>ECMAScript 5th Edition</td>
  </tr>
 </tbody>
</table>
<h2 id="Syntax" name="Syntax">Syntax</h2>
<pre class="syntaxbox">
<code><em>array</em>.filter(<em>callback</em>[, <em>thisObject</em>])</code></pre>
<h3 id="Parameters" name="Parameters">Parameters</h3>
<dl>
 <dt>
  <code>callback</code></dt>
 <dd>
  Function to test each element of the array.</dd>
 <dt>
  <code>thisObject</code></dt>
 <dd>
  Object to use as <code>this</code> when executing <code>callback</code>.</dd>
</dl>
<h2 id="Description" name="Description">Description</h2>
<p><code>filter</code> calls a provided <code>callback</code> function once for each element in an array, and constructs a new array of all the values for which <code>callback</code> returns a true value. <code>callback</code> is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the <code>callback</code> test are simply skipped, and are not included in the new array.</p>
<p><code>callback</code> is invoked with three arguments:</p>
<ol style="margin-left: 40px;">
 <li>the value of the element</li>
 <li>the index of the element</li>
 <li>the Array object being traversed</li>
</ol>
<p>If a <code>thisObject</code> parameter is provided to <code>filter</code>, it will be used as the <code>this</code> for each invocation of the <code>callback</code>. If it is not provided, or is <code>null</code>, the global object associated with <code>callback</code> is used instead.</p>
<p><code>filter</code> does not mutate the array on which it is called.</p>
<p>The range of elements processed by <code>filter</code> is set before the first invocation of <code>callback</code>. Elements which are appended to the array after the call to <code>filter</code> begins will not be visited by <code>callback</code>. If existing elements of the array are changed, or deleted, their value as passed to <code>callback</code> will be the value at the time <code>filter</code> visits them; elements that are deleted are not visited.</p>
<h2 id="Compatibility" name="Compatibility">Compatibility</h2>
<p><code>filter</code> is a JavaScript extension 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>filter</code> in ECMA-262 implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming that <code>fn.call</code> evaluates to the original value of <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/call" title="JavaScript/Reference/Global Objects/Function/call">Function.prototype.call</a></code>, and that <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/push" title="JavaScript/Reference/Global Objects/Array/push">Array.prototype.push</a></code> has its original value.</p>
<!-- var DO_NOT_MODIFY_THE_FOLLOWING_CODE_IN_ANY_WAY = 0; -->
<pre>
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: <a class="external" href="http://es5.github.com/#x15.4.4.18" rel="freelink">http://es5.github.com/#x15.4.4.18</a>
if ( !Array.prototype.forEach ) {

  Array.prototype.forEach = function( callback, thisArg ) {

    var T, k;

    if ( this == null ) {
      throw new TypeError( " this is null or not defined" );
    }

    // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the <a href="https://developer.mozilla.org/Get" title="Get">Get</a> internal method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length &gt;&gt;&gt; 0; // Hack to convert O.length to a UInt32

    // 4. If IsCallable(callback) is false, throw a TypeError exception.
    // See: <a class="external" href="http://es5.github.com/#x9.11" rel="freelink">http://es5.github.com/#x9.11</a>
    if ( {}.toString.call(callback) != "[object Function]" ) {
      throw new TypeError( callback + " is not a function" );
    }

    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    if ( arguments.length &gt; 1 ) {
      T = thisArg;
    }

    // 6. Let k be 0
    k = 0;

    // 7. Repeat, while k &lt; len
    while( k &lt; len ) {

      var kValue;

      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the <a href="https://developer.mozilla.org/HasProperty" title="HasProperty">HasProperty</a> internal method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      if ( k in O ) {

        // i. Let kValue be the result of calling the <a href="https://developer.mozilla.org/Get" title="Get">Get</a> internal method of O with argument Pk.
        kValue = O[ k ];

        // ii. Call the <a href="https://developer.mozilla.org/Call" title="Call">Call</a> internal method of callback with T as the this value and
        // argument list containing kValue, k, and O.
        callback.call( T, kValue, k, O );
      }
      // d. Increase k by 1.
      k++;
    }
    // 8. return undefined
  };
}</pre>
<h2 id="Examples" name="Examples">Examples</h2>
<h3 id="Example:_Filtering_out_all_small_values" name="Example:_Filtering_out_all_small_values">Example: Filtering out all small values</h3>
<p>The following example uses <code>filter</code> to create a filtered array that has all elements with values less than 10 removed.</p>
<pre class="brush: js">
function isBigEnough(element) {
  return element &gt;= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44] 
</pre>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>Based on <a class="external" href="http://kangax.github.com/es5-compat-table/">Kangax's compat tables</a></p>
<p>{{ CompatibilityTable() }}</p>
<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>{{ CompatVersionUnknown() }}</td>
    <td>9</td>
    <td>{{ CompatVersionUnknown() }}</td>
    <td>{{ CompatVersionUnknown() }}</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>
<p>&nbsp;</p>
Revert to this revision