lastIndexOf method
The lastIndexOf method searches
for an element in an array. It returns
the number of the last element found,
or -1 if there is no such element. The
first parameter is the element text,
the second (optional) is the position
from which to start the search. The
search is carried out from the end
of the array to the beginning.
Syntax
array.lastIndexOf(element, [where to start]);
Example
Let's find the position of the last three in the array:
let arr = [1, 2, 3, 3, 3, 4, 5];
let res = arr.lastIndexOf(3);
console.log(res);
The code execution result:
4
Example
Now let's try to find an element that is not in an array:
let arr = [1, 2, 3, 4, 5];
let res = arr.lastIndexOf(6);
console.log(res);
The code execution result:
-1
Example
Let's start searching from a given position. As a result, the last three will be found, except for the missing ones:
let arr = [1, 2, 3, 3, 4, 5, 3];
let res = arr.lastIndexOf(3, 4);
console.log(res);
The code execution result:
3