Array. prototype. lastIndexOf()
Returns the index of the last occurrence of a value in the array, or -1 when it isn’t there.
- Returns
- The index of the last occurrence, or
-1. - Changes the original
- No
Example
#const answers = ['A', 'C', 'B', 'C', 'D']
console.log(answers.lastIndexOf('C'))
console.log(answers.indexOf('C'))
console.log(answers.lastIndexOf('E'))Definition and usage
#The lastIndexOf() method searches the array from the end and returns the index of the last element equal to the given value. When that value isn’t there, the result is -1. The index is always counted from the start of the array, even though the search itself runs backward.
It compares strictly, like the === operator: the number 3 and the string "3" are different values to it, and NaN is never found. Objects are compared by reference, so to find an object by one of its fields, use findLastIndex() instead.
The second argument marks the index the search starts from, moving toward the beginning. That lets you find the second-to-last occurrence, or limit the search to the array’s early part.
Syntax
#array.lastIndexOf(searchElement)
array.lastIndexOf(searchElement, fromIndex)Parameters
#searchElement
any value
The value to search for.fromIndex
optional
The index the search starts from, moving toward the beginning. Defaults to the last element. A negative value counts from the end.
More examples
#const logins = ['emma', 'jack', 'emma', 'mia', 'emma']
const last = logins.lastIndexOf('emma')
const previous = logins.lastIndexOf('emma', last - 1)
console.log(last, previous)const tags = ['html', 'css', 'js', 'css']
const isUnique = (tag) => tags.indexOf(tag) === tags.lastIndexOf(tag)
console.log(isUnique('html'))
console.log(isUnique('css'))const values = [1, NaN, 3]
console.log(values.lastIndexOf(NaN))
console.log(values.findLastIndex(Number.isNaN))lastIndexOf() compares with ===, and NaN isn’t even equal to itself. findLastIndex() can handle it with the Number.isNaN function.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Compare the result explicitly against
-1. Index0is also a valid match, but it behaves like false in anifcondition. - Comparing
indexOf(x) === lastIndexOf(x)shows whether a value has no duplicates. Remember that for a value that isn’t there at all, both results are-1.
Related entries
#- Array.prototype.indexOf()Returns the index of the first occurrence of a value, or -1.
- Array.prototype.findLastIndex()Returns the index of the last element matching a condition, searching from the end, or -1.
- Array.prototype.includes()Checks whether an array contains the given value.
- String.prototype.lastIndexOf()Returns the index of the last occurrence of the given text in a string, or -1 when it is not there.
Spotted a mistake or missing an example? Write to us.