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 1131417 of Array.prototype.find()

  • Revision slug: Web/JavaScript/Reference/Global_Objects/Array/find
  • Revision title: Array.prototype.find()
  • Revision id: 1131417
  • Created:
  • Creator: tjcrowder
  • Is current revision? No
  • Comment Update polyfill not to create an enumerable property on Array.prototype

Revision Content

{{JSRef}}

The find() method returns a value in the array, if an element in the array satisfies the provided testing function. Otherwise {{jsxref("undefined")}} is returned.

See also the {{jsxref("Array.findIndex", "findIndex()")}} method, which returns the index of a found element in the array instead of its value.

Syntax

arr.find(callback[, thisArg])

Parameters

callback
Function to execute on each value in the array, 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. Object to use as this when executing callback.

Return value

A value in the array if an element passes the test; otherwise, {{jsxref("undefined")}}.

Description

The find method executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element. Otherwise, find returns {{jsxref("undefined")}}. 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.

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

If a thisArg parameter is provided to find, it will be used as the this for each invocation of the callback. If it is not provided, then {{jsxref("undefined")}} is used.

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

The range of elements processed by find is set before the first invocation of callback. Elements that are appended to the array after the call to find begins will not be visited by callback. If an existing, unvisited element of the array is changed by callback, its value passed to the visiting callback will be the value at the time that find visits that element's index; elements that are deleted are not visited.

Examples

Find an object in an array by one of its properties

var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

function findCherries(fruit) { 
    return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }

Find a prime number in an array

The following example finds an element in the array that is a prime number (or returns {{jsxref("undefined")}} if there is no prime number).

function isPrime(element, index, array) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false;
    }
  }
  return element > 1;
}

console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5

Polyfill

This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet. However, you can polyfill Array.prototype.find with the following snippet:

if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, "find", {
    value: function(predicate) {
     'use strict';
     if (this == null) {
       throw new TypeError('Array.prototype.find called on null or undefined');
     }
     if (typeof predicate !== 'function') {
       throw new TypeError('predicate must be a function');
     }
     var list = Object(this);
     var length = list.length >>> 0;
     var thisArg = arguments[1];
     var value;

     for (var i = 0; i < length; i++) {
       value = list[i];
       if (predicate.call(thisArg, value, i, list)) {
         return value;
       }
     }
     return undefined;
    }
  });
}

If you need to support truly obsolete JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable.

Specifications

Specification Status Comment
{{SpecName('ES6', '#sec-array.prototype.find', 'Array.prototype.find')}} {{Spec2('ES6')}} Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}} {{Spec2('ESDraft')}}  

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Edge Opera Safari
Basic support {{CompatChrome(45.0)}} {{CompatGeckoDesktop("25.0")}} {{CompatNo}} 12 {{CompatOpera(32.0)}} {{CompatSafari("7.1")}}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Edge Opera Mobile Safari Mobile
Basic support {{CompatNo}} {{CompatNo}} {{CompatGeckoMobile("25.0")}} {{CompatNo}} 12 {{CompatNo}} 8.0

See also

  • {{jsxref("Array.prototype.findIndex()")}}
  • {{jsxref("Array.prototype.every()")}}

Revision Source

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

<p>The <code><strong>find()</strong></code> method returns a <strong>value</strong> in the array, if an element in the array satisfies the provided testing function. Otherwise {{jsxref("undefined")}} is returned.</p>

<p>See also the {{jsxref("Array.findIndex", "findIndex()")}} method, which returns the <strong>index</strong> of a found element in the array instead of its value.</p>

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

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

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

<dl>
 <dt><code>callback</code></dt>
 <dd>Function to execute on each value in the array, taking three arguments:
 <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 <code>find</code> was called upon.</dd>
 </dl>
 </dd>
 <dt><code>thisArg</code></dt>
 <dd>Optional. Object to use as <code>this</code> when executing <code>callback</code>.</dd>
</dl>

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

<p>A value in the array if an element passes the test; otherwise, {{jsxref("undefined")}}.</p>

<h2 id="Description">Description</h2>

<p>The <code>find</code> method executes the <code>callback</code> function once for each element present in the array until it finds one where <code>callback</code> returns a true value. If such an element is found, <code>find</code> immediately returns the value of that element. Otherwise, <code>find</code> returns {{jsxref("undefined")}}. <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.</p>

<p><code>callback</code> is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.</p>

<p>If a <code>thisArg</code> parameter is provided to <code>find</code>, it will be used as the <code>this</code> for each invocation of the <code>callback</code>. If it is not provided, then {{jsxref("undefined")}} is used.</p>

<p><code>find</code> does not mutate the array on which it is called.</p>

<p>The range of elements processed by <code>find</code> is set before the first invocation of <code>callback</code>. Elements that are appended to the array after the call to <code>find</code> begins will not be visited by <code>callback</code>. If an existing, unvisited element of the array is changed by <code>callback</code>, its value passed to the visiting <code>callback</code> will be the value at the time that <code>find</code> visits that element's index; elements that are deleted are not visited.</p>

<h2 id="Examples">Examples</h2>

<h3 id="Find_an_object_in_an_array_by_one_of_its_properties">Find an object in an array by one of its properties</h3>

<pre class="brush: js">
var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

function findCherries(fruit) { 
    return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }</pre>

<h3 id="Find_a_prime_number_in_an_array">Find a prime number in an array</h3>

<p>The following example finds an element in the array that is a prime number (or returns {{jsxref("undefined")}} if there is no prime number).</p>

<pre class="brush: js">
function isPrime(element, index, array) {
  var start = 2;
  while (start &lt;= Math.sqrt(element)) {
    if (element % start++ &lt; 1) {
      return false;
    }
  }
  return element &gt; 1;
}

console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5
</pre>

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

<p>This method has been added to the ECMAScript 2015&nbsp;specification and may not be available in all JavaScript implementations yet. However, you can polyfill <code>Array.prototype.find</code> with the following snippet:</p>

<pre class="brush: js">
if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, "find", {
    value: function(predicate) {
     'use strict';
     if (this == null) {
       throw new TypeError('Array.prototype.find called on null or undefined');
     }
     if (typeof predicate !== 'function') {
       throw new TypeError('predicate must be a function');
     }
     var list = Object(this);
     var length = list.length >>> 0;
     var thisArg = arguments[1];
     var value;

     for (var i = 0; i < length; i++) {
       value = list[i];
       if (predicate.call(thisArg, value, i, list)) {
         return value;
       }
     }
     return undefined;
    }
  });
}
</pre>

<p>If you need to support truly obsolete JavaScript engines that don't support <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, it's best not to polyfill <code>Array.prototype</code> methods at all, as you can't make them non-enumerable.</p>

<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('ES6', '#sec-array.prototype.find', 'Array.prototype.find')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>Initial definition.</td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}</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>Edge</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatChrome(45.0)}}</td>
   <td>{{CompatGeckoDesktop("25.0")}}</td>
   <td>{{CompatNo}}</td>
   <td>12</td>
   <td>{{CompatOpera(32.0)}}</td>
   <td>{{CompatSafari("7.1")}}</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>Edge</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatGeckoMobile("25.0")}}</td>
   <td>{{CompatNo}}</td>
   <td>12</td>
   <td>{{CompatNo}}</td>
   <td>8.0</td>
  </tr>
 </tbody>
</table>
</div>

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

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