Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1109667 of Array.prototype.filter()

  • Revision slug: Web/JavaScript/Reference/Global_Objects/Array/filter
  • Revision title: Array.prototype.filter()
  • Revision id: 1109667
  • Created:
  • Creator: codeangler
  • Is current revision? No
  • Comment

Revision Content

{{JSRef}}

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Syntax

var new_array = arr.filter(callback[, thisArg])

Parameters

callback
Function to test each element of the array. Return true to keep the element, false otherwise, taking three arguments:
element
The current element being processed in the array.
index
The index of the current element being processed in the array.
array
The array find was called upon.
thisArg
Optional. Value to use as this when executing callback.

Return value

A new array with the elements that pass the test.

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 value that coerces to true. 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 thisArg parameter is provided to filter, it will be passed to callback when invoked, for use as its this value.  Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

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.

Examples

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(value) {
  return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

Filtering invalid entries from JSON

The following example uses filter() to create a filtered json of all elements with non-zero, numeric id.

var arr = [
  { id: 15 },
  { id: -1 },
  { id: 0 },
  { id: 3 },
  { id: 12.2 },
  { },
  { id: null },
  { id: NaN },
  { id: 'undefined' }
];

var invalidEntries = 0;

function filterByID(obj) {
  if ('id' in obj && typeof(obj.id) === 'number' && !isNaN(obj.id)) {
    return true;
  } else {
    invalidEntries++;
    return false;
  }
}

var arrByID = arr.filter(filterByID);

console.log('Filtered Array\n', arrByID); 
// Filtered Array
// [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }]

console.log('Number of Invalid Entries = ', invalidEntries); 
// Number of Invalid Entries = 4

Polyfill

filter() was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all 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 {{jsxref("Function.prototype.call()")}}, and that {{jsxref("Array.prototype.push()")}} has its original value.

if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun/*, thisArg*/) {
    'use strict';

    if (this === void 0 || this === null) {
      throw new TypeError();
    }

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== 'function') {
      throw new TypeError();
    }

    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++) {
      if (i in t) {
        var val = t[i];

        // NOTE: Technically this should Object.defineProperty at
        //       the next index, as push can be affected by
        //       properties on Object.prototype and Array.prototype.
        //       But that method's new, and collisions should be
        //       rare, so use the more-compatible alternative.
        if (fun.call(thisArg, val, i, t)) {
          res.push(val);
        }
      }
    }

    return res;
  };
}

Specifications

Specification Status Comment
{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}} {{Spec2('ES5.1')}} Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.filter', 'Array.prototype.filter')}} {{Spec2('ES6')}}  
{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}} {{Spec2('ESDraft')}}  

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{CompatVersionUnknown}} {{CompatGeckoDesktop("1.8")}} {{CompatIE("9")}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatGeckoMobile("1.8")}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}

See also

  • {{jsxref("Array.prototype.forEach()")}}
  • {{jsxref("Array.prototype.every()")}}
  • {{jsxref("Array.prototype.some()")}}
  • {{jsxref("Array.prototype.reduce()")}}

Revision Source

<div>{{JSRef}}</div>

<p>The <code><strong>filter()</strong></code> method creates a new array with all elements that pass the test implemented by the provided function.</p>

<h2 id="Syntax">Syntax</h2>

<pre class="syntaxbox">
<code><var>var new_array = arr</var>.filter(<var>callback</var>[, <var>thisArg</var>])</code></pre>

<h3 id="Parameters">Parameters</h3>

<dl>
 <dt><code>callback</code></dt>
 <dd>Function to test each element of the array. Return <code>true</code> to keep the element, <code>false</code> otherwise, taking three arguments:</dd>
 <dd>
 <dl>
  <dt><code>element</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&nbsp;<code>find</code>&nbsp;was called upon.</dd>
 </dl>
 </dd>
 <dt><code>thisArg</code></dt>
 <dd>Optional. Value to use as <code>this</code> when executing <code>callback</code>.</dd>
</dl>

<h3 id="Return_value">Return value</h3>

<p>A new array with the elements that pass the test.</p>

<h2 id="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 href="/en-US/docs/Glossary/Truthy">a value that coerces to <code>true</code></a>. <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>
 <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>thisArg</code> parameter is provided to <code>filter</code>, it will be passed to <code>callback</code> when invoked, for use as its <code>this</code> value.&nbsp; Otherwise, the value <code>undefined</code> will be passed for use as its <code>this</code> value. The <code>this</code> value ultimately observable by <code>callback</code> is determined according to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">the usual rules for determining the <code>this</code> seen by a function</a>.</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="Examples">Examples</h2>

<h3 id="Filtering_out_all_small_values">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(value) {
  return value &gt;= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
</pre>

<h3 id="Filtering_invalid_entries_from_JSON">Filtering invalid entries from JSON</h3>

<p>The following example uses <code>filter()</code> to create a filtered json of all elements with non-zero, numeric <code>id</code>.</p>

<pre class="brush: js">
var arr = [
  { id: 15 },
  { id: -1 },
  { id: 0 },
  { id: 3 },
  { id: 12.2 },
  { },
  { id: null },
  { id: NaN },
  { id: 'undefined' }
];

var invalidEntries = 0;

function filterByID(obj) {
  if ('id' in obj &amp;&amp; typeof(obj.id) === 'number' &amp;&amp; !isNaN(obj.id)) {
    return true;
  } else {
    invalidEntries++;
    return false;
  }
}

var arrByID = arr.filter(filterByID);

console.log('Filtered Array\n', arrByID); 
// Filtered Array
// [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }]

console.log('Number of Invalid Entries = ', invalidEntries); 
// Number of Invalid Entries = 4
</pre>

<h2 id="Polyfill">Polyfill</h2>

<p><code>filter()</code> was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all 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 {{jsxref("Function.prototype.call()")}}, and that {{jsxref("Array.prototype.push()")}} has its original value.</p>

<pre class="brush: js">
if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun/*, thisArg*/) {
    'use strict';

    if (this === void 0 || this === null) {
      throw new TypeError();
    }

    var t = Object(this);
    var len = t.length &gt;&gt;&gt; 0;
    if (typeof fun !== 'function') {
      throw new TypeError();
    }

    var res = [];
    var thisArg = arguments.length &gt;= 2 ? arguments[1] : void 0;
    for (var i = 0; i &lt; len; i++) {
      if (i in t) {
        var val = t[i];

        // NOTE: Technically this should Object.defineProperty at
        //       the next index, as push can be affected by
        //       properties on Object.prototype and Array.prototype.
        //       But that method's new, and collisions should be
        //       rare, so use the more-compatible alternative.
        if (fun.call(thisArg, val, i, t)) {
          res.push(val);
        }
      }
    }

    return res;
  };
}
</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>Initial definition. Implemented in JavaScript 1.6.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-array.prototype.filter', 'Array.prototype.filter')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>&nbsp;</td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td>&nbsp;</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<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.8")}}</td>
   <td>{{CompatIE("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>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoMobile("1.8")}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="See_also">See also</h2>

<ul>
 <li>{{jsxref("Array.prototype.forEach()")}}</li>
 <li>{{jsxref("Array.prototype.every()")}}</li>
 <li>{{jsxref("Array.prototype.some()")}}</li>
 <li>{{jsxref("Array.prototype.reduce()")}}</li>
</ul>
Revert to this revision