Getting the index of the last matching item in an array with vanilla JS
Let’s say you have an an array with a list of awesome wizards.
let wizards = ['Gandalf', 'Merlin', 'Radagast', 'Merlin'];
You’ll notice that Merlin
appears in the list twice. You can get the index of the first instance of Merlin
using the Array.indexOf()
method.
// returns 1
let index = wizards.indexOf('Merlin');
But what if you wanted to get the index of the last instance of Merlin
in the wizards
array instead? For that, we can use the Array.lastIndexOf()
method.
Just like with Array.indexOf()
, pass in the item to get as an argument. It returns the index of the last instance of that item, or -1
if it doesn’t exist.
// returns 3
let lastIndex = wizards.lastIndexOf('Merlin');
If there’s only one instance of an item, it still works.
// returns 0
let gandalf = wizards.lastIndexOf('Gandalf');