Array.prototype.indexOf()

  • Revision slug: JavaScript/Reference/Global_Objects/Array/indexOf
  • Revision title: Array indexOf method
  • Revision id: 29229
  • Created:
  • Creator: jdalton
  • Is current revision? No
  • Comment page display name changed to 'Array indexOf method'

Revision Content

 

Summary

Returns the first index at which a given element can be found in the array, or -1 if it is not present.

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

Syntax

array.indexOf(searchElement[, fromIndex])

Parameters

searchElement
Element to locate in the array.
fromIndex
The index at which to begin the search. Defaults to 0, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, -1 is returned, i.e. the array will not be searched. If negative, it is taken as the offset from the end of the array. Note that even when the index is negative, the array is still searched from front to back. If the calculated index is less than 0, the whole array will be searched.

Description

indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

Compatibility

indexOf is a recent addition to the ECMA-262 standard; as such it may not be present in all browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of indexOf in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming ObjectTypeErrorNumber, Math.floor, Math.abs, and Math.max have their original value.  {{ var DO_NOT_MODIFY_THE_FOLLOWING_CODE_IN_ANY_WAY = 0; }}

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}

Examples

Example: Using indexOf

The following example uses indexOf to locate values in an array.

var array = [2, 5, 9];
var index = array.indexOf(2);
// index is 0
index = array.indexOf(7);
// index is -1

Example: Finding all the occurrences of an element

The following example uses indexOf to find all the indices of an element in a given array, using push to add them to another array as they are found.

var indices = [];
var idx = array.indexOf(element);
while (idx != -1) {
    indices.push(idx);
    idx = array.indexOf(element, idx + 1);
}

Browser compatibility

Based on Kangax's compat tables

{{ CompatibilityTable() }}

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

See also

lastIndexOf

{{ languages( { "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/Array/indexOf", "ja": "ja/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/Array/indexOf" } ) }}

Revision Source

<p> </p>
<h3 name="Summary">Summary</h3>
<p>Returns the first index at which a given element can be found in the array, or -1 if it is not present.</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.6</td> </tr> <tr> <td>ECMAScript Edition</td> <td>ECMAScript 5th Edition</td> </tr> </tbody>
</table>
<h3 name="Syntax">Syntax</h3>
<p><code><em>array</em>.indexOf(<em>searchElement</em>[, <em>fromIndex</em>])</code></p>
<h3 name="Parameters">Parameters</h3>
<dl> <dt><code>searchElement</code></dt> <dd>Element to locate in the array.</dd> <dt><code>fromIndex</code></dt> <dd>The index at which to begin the search. Defaults to 0, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, -1 is returned, i.e. the array will not be searched. If negative, it is taken as the offset from the end of the array. Note that even when the index is negative, the array is still searched from front to back. If the calculated index is less than 0, the whole array will be searched.</dd>
</dl>
<h3 name="Description">Description</h3>
<p><code>indexOf</code> compares <code>searchElement</code> to elements of the Array using <a href="/en/JavaScript/Reference/Operators/Comparison_Operators#Using_the_Equality_Operators" title="en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators#Using_the_Equality_Operators">strict equality</a> (the same method used by the ===, or triple-equals, operator).</p>
<h3 name="Compatibility">Compatibility</h3>
<p><code>indexOf</code> is a recent addition to the ECMA-262 standard; as such it may not be present in all browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>indexOf</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>, <code style="color: inherit; font-weight: inherit; ">TypeError</code>, <code>Number</code>, <code>Math.floor</code>, <code>Math.abs</code>, and <code>Math.max</code> have their original value.  {{ var DO_NOT_MODIFY_THE_FOLLOWING_CODE_IN_ANY_WAY = 0; }}</p>
<pre class="brush: js">if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length &gt;&gt;&gt; 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length &gt; 0) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 &amp;&amp; n != Infinity &amp;&amp; n != -Infinity) {
                n = (n &gt; 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n &gt;= len) {
            return -1;
        }
        var k = n &gt;= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k &lt; len; k++) {
            if (k in t &amp;&amp; t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}
</pre>
<h3 name="Examples">Examples</h3>
<h4 name="Example:_Using_indexOf">Example: Using indexOf</h4>
<p>The following example uses <code>indexOf</code> to locate values in an array.</p>
<pre class="brush: js">var array = [2, 5, 9];
var index = array.indexOf(2);
// index is 0
index = array.indexOf(7);
// index is -1
</pre>
<h4 name="Example:_Finding_all_the_occurrences_of_an_element">Example: Finding all the occurrences of an element</h4>
<p>The following example uses <code>indexOf</code> to find all the indices of an element in a given array, using <a href="/en/JavaScript/Reference/Global_Objects/Array/push" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Array/push">push</a> to add them to another array as they are found.</p>
<div style="text-align: left; "> <pre class="brush: js">var indices = [];
var idx = array.indexOf(element);
while (idx != -1) {
    indices.push(idx);
    idx = array.indexOf(element, idx + 1);
}</pre>
</div>
<h3>Browser compatibility</h3>
<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>Firefox (Gecko)</th> <th>Chrome</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>Firefox Mobile (Gecko)</th> <th>Android</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> </tr> </tbody> </table>
</div>
<h3 name="See_also">See also</h3>
<p><a href="/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Array/lastIndexOf">lastIndexOf</a></p>
<p>{{ languages( { "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/Array/indexOf", "ja": "ja/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/Array/indexOf" } ) }}</p>
Revert to this revision