In this article, you will learn about the javascript Array built-in method Array.prototype.lastIndexOf()
. How does this method work in javascript?
This Array.prototype.lastIndexOf()
method returns the last index at which a given element can be found in the array, otherwise, it returns -1 if the element is not present in an array. The array is searched right to left, starting at fromIndex.
array.lastIndexOf(searchElement, fromIndex);
This method takes 2 parameters as given below:
searchElement
from backward. Negative fromIndex
values count from the last element and it still searches from right to left. If the index is greater than or equal to the array's length, then it returns -1
, which means the array will not be searched. You cannot use lastIndexOf()
to search for empty slots in a sparse array, it returns -1
.
Here are some examples of Array.prototype.lastIndexOf()
method:
const arr = ['Java', 'C#', 'Python', 'SQL Server', 'GO', 'JavaScript'];
console.log(arr.lastIndexOf("Python"));
// Output => 2
console.log(arr.lastIndexOf("Python", 3))
// Output => 2
console.log(arr.lastIndexOf("Python", -1))
// Output => 2
//Sparse array
//You cannot use lastIndexOf() to search for empty slots in a sparse array, it returns -1.
const sparseArray = ['Java', , 'Python', , 'GO', 'JavaScript'];
console.log(sparseArray.lastIndexOf(undefined));
// Output => -1
I hope this article will help you to understand the javascript Array built-in method Array.prototype.lastIndexOf().
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments