Array.prototype.lastIndexOf()

  • Revision slug: JavaScript/Reference/Global_Objects/Array/lastIndexOf
  • Revision title: Array lastIndexOf method
  • Revision id: 29170
  • Created:
  • Creator: evilpie
  • Is current revision? No
  • Comment 1 words added, 7 words removed

Revision Content

 

Returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.

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

Syntax

array.lastIndexOf(searchElement[, fromIndex])

Parameters

searchElement 
Element to locate in the array.
fromIndex 
The index at which to start searching backwards. Defaults to the array's length, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, the whole array will 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 back to front. If the calculated index is less than 0, -1 is returned, i.e. the array will not be searched.

Description

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

Compatibility

lastIndexOf is a recent addition 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 lastIndexOf 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.min have their original values. {{ var DO_NOT_MODIFY_THE_FOLLOWING_CODE_IN_ANY_WAY = 0; }}

if (!Array.prototype.lastIndexOf)
{
  Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/)
  {
    "use strict";

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

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = len;
    if (arguments.length > 1)
    {
      n = Number(arguments[1]);
      if (n !== n)
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    var k = n >= 0
          ? Math.min(n, len - 1)
          : len - Math.abs(n);

    for (; k >= 0; k--)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
}

Again, note that this implementation aims for absolute compatibility with lastIndexOf in Firefox and the SpiderMonkey JavaScript engine, including in several cases which are arguably edge cases. If you intend to use this in real-world applications, you may be able to calculate from with less complicated code if you ignore those cases.

Examples

Example: Using lastIndexOf

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

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

Example: Finding all the occurrences of an element

The following example uses lastIndexOf 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.lastIndexOf(element);
while (idx != -1)
{
  indices.push(idx);
  idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1);
}

Note that we have to handle the case idx == 0 separately here because the element will always be found regardless of the fromIndex parameter if it is the first element of the array. This is different from the indexOf method.

See also

indexOf

 

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

Revision Source

<p> </p>
<p>Returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at <code>fromIndex</code>.</p>
<table class="standard-table"> <thead> <tr> <th class="header" colspan="2">Method of <a href="/en/JavaScript/Reference/Global_Objects/Array"><code>Array</code></a></th> </tr> </thead> <tbody> <tr> <td>Implemented in</td> <td>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>.lastIndexOf(<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 start searching backwards. Defaults to the array's length, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, the whole array will 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 back to front. If the calculated index is less than 0, -1 is returned, i.e. the array will not be searched.</dd>
</dl>
<h3 name="Description">Description</h3>
<p><code>lastIndexOf</code> compares <code>searchElement</code> to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).</p>
<h3 name="Compatibility">Compatibility</h3>
<p><code>lastIndexOf</code> is a recent addition 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>lastIndexOf</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.min</code> have their original values. {{ var DO_NOT_MODIFY_THE_FOLLOWING_CODE_IN_ANY_WAY = 0; }}</p>
<pre class="brush: js">if (!Array.prototype.lastIndexOf)
{
  Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/)
  {
    "use strict";

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

    var t = Object(this);
    var len = t.length &gt;&gt;&gt; 0;
    if (len === 0)
      return -1;

    var n = len;
    if (arguments.length &gt; 1)
    {
      n = Number(arguments[1]);
      if (n !== n)
        n = 0;
      else if (n !== 0 &amp;&amp; n !== (1 / 0) &amp;&amp; n !== -(1 / 0))
        n = (n &gt; 0 || -1) * Math.floor(Math.abs(n));
    }

    var k = n &gt;= 0
          ? Math.min(n, len - 1)
          : len - Math.abs(n);

    for (; k &gt;= 0; k--)
    {
      if (k in t &amp;&amp; t[k] === searchElement)
        return k;
    }
    return -1;
  };
}
</pre>
<p>Again, note that this implementation aims for absolute compatibility with <code>lastIndexOf</code> in Firefox and the SpiderMonkey JavaScript engine, including in several cases which are arguably edge cases. If you intend to use this in real-world applications, you may be able to calculate <code>from</code> with less complicated code if you ignore those cases.</p>
<h3 name="Examples">Examples</h3>
<h4 name="Example:_Using_lastIndexOf">Example: Using lastIndexOf</h4>
<p>The following example uses <code>lastIndexOf</code> to locate values in an array.</p>
<pre class="eval">var array = [2, 5, 9, 2];
var index = array.lastIndexOf(2);
// index is 3
index = array.lastIndexOf(7);
// index is -1
index = array.lastIndexOf(2, 3);
// index is 3
index = array.lastIndexOf(2, 2);
// index is 0
index = array.lastIndexOf(2, -2);
// index is 0
index = array.lastIndexOf(2, -1);
// index is 3
</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>lastIndexOf</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>
<pre class="eval">var indices = [];
var idx = array.lastIndexOf(element);
while (idx != -1)
{
  indices.push(idx);
  idx = (idx &gt; 0 ? array.lastIndexOf(element, idx - 1) : -1);
}
</pre>
<p>Note that we have to handle the case <code>idx == 0</code> separately here because the element will always be found regardless of the <code>fromIndex</code> parameter if it is the first element of the array. This is different from the <a href="/en/JavaScript/Reference/Global_Objects/Array/indexOf" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf">indexOf</a> method.</p>
<h3 name="See_also">See also</h3>
<p><a href="/en/JavaScript/Reference/Global_Objects/Array/indexOf" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf">indexOf</a></p>
<p> </p>
<p>{{ languages( { "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/Array/lastIndexOf", "ja": "ja/Core_JavaScript_1.5_Reference/Global_Objects/Array/lastIndexOf", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/Array/lastIndexOf" } ) }}</p>
Revert to this revision