How to search a Javascript array from the end

Description

lastIndexOf syntax:


lastIndexOf(itemToLookFor, optionalIndexToStartWith)

lastIndexOf() starts from the back of the array to do the search. lastIndexOf() returns the position of the item in the array or -1 if the item isn't in the array.

An identity comparison is used during comparing.

Example


var numbers = [1,2,3,4,5,4,3,2,1]; 
console.log(numbers.lastIndexOf(4)); //5 
console.log(numbers.lastIndexOf(4, 4)); //3 
// www .j  a va  2s  .c  om

var person = { name: "JavaScript" }; 
var people = [{ name: "JavaScript" }]; 

var morePeople = [person]; 
console.log(morePeople.indexOf(person)); //0 

The code above generates the following result.





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window