Javascript Array lastIndexOf()

Introduction

Javascript array lastIndexOf() method searches array to get the last index of a given element.

It returns -1 if not found.

The array is searched backwards, starting at fromIndex.

arr.lastIndexOf(searchElement[, fromIndex])
  • searchElement - element to search.
  • fromIndex - Optional, the index to start searching backwards.

fromIndex defaults to the array's length minus one.

If fromIndex 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.

Search an array for the item "Java":

var languages = ["CSS", "HTML", "Java", "Javascript"];
var a = languages.lastIndexOf("Java");
console.log(a);/*w  ww .j  a  v  a 2s.  com*/

Search an array for the item "Java", starting the search at position 4:

var languages = ["CSS", "HTML", "Java", "Javascript", "CSS", "HTML", "Java", "Javascript"];
var a = languages.lastIndexOf("Java", 4);
console.log(a);// w  w  w .  j a va  2  s .com

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

var numbers = [2, 7, 9, 2];
let a = numbers.lastIndexOf(2);     
console.log(a);/*from w  w  w.  j a va  2 s.  c  o  m*/
a = numbers.lastIndexOf(7);
console.log(a);
a = numbers.lastIndexOf(2, 3);
console.log(a);
a = numbers.lastIndexOf(2, 2);
console.log(a);
a = numbers.lastIndexOf(2, -2);
console.log(a);
a = numbers.lastIndexOf(2, -1); 
console.log(a);

Finding all the occurrences of an element

var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.lastIndexOf(element);
while (idx  != -1) {
  indices.push(idx);/*from   w  w w .  j ava 2s  . co  m*/
  idx = idx > 0 ? array.lastIndexOf(element, idx - 1) : -1;
}

console.log(indices);// [4, 2, 0]

More example

let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];

console.log(numbers.indexOf(4)); // 3 
console.log(numbers.lastIndexOf(4)); // 5 
console.log(numbers.includes(4)); // true 

console.log(numbers.indexOf(4, 4)); // 5 
console.log(numbers.lastIndexOf(4, 4)); // 3 
console.log(numbers.includes(4, 7)); // false 

let person = {/*from  w  w w. java2  s . c  om*/
    name: "HTML"
};
let people = [{
    name: "HTML"
}];
let morePeople = [person];

console.log(people.indexOf(person)); // -1 
console.log(morePeople.indexOf(person)); // 0 
console.log(people.includes(person)); // false 
console.log(morePeople.includes(person)); // true 



PreviousNext

Related