This content originally appeared on Go Make Things and was authored by Go Make Things
Yesterday, we learned how to find the first matching item in an array. Today, we’re going to learn how to find the index of an item in an array instead of the item itself.
Let’s dig in!
The Array.prototype.indexOf()
method
The Array.prototype.indexOf()
method accepts the item you want to find as an argument, and returns the index of that item. If no matching item is found, it returns -1
instead.
let wizards = ['Merlin', 'Gandalf', 'Ursula', 'Radgast'];
// returns 1
let index = wizards.indexOf('Gandalf');
// returns -1
let anotherIndex = wizards.indexOf('Morgana');
The Array.prototype.indexOf()
method is great, but only works for matching primitive array values. It won’t match nested arrays or objects inside the array.
For example, imagine if your wizards
array instead looked like this.
let wizards = [
{
name: 'Merlin',
color: 'blue'
},
{
name: 'Gandalf',
color: 'gray'
},
{
name: 'Ursula',
color: 'purple'
},
{
name: 'Radagast',
color: 'brown'
}
];
You want to find the index for Gandalf
, so you pass in an object, like this.
// returns -1
let index = wizards.indexOf({
name: 'Gandalf',
color: 'gray'
});
Here, index
will have a value of -1
, because it cannot match against objects.
The Array.prototype.findIndex()
method
This is where the Array.prototype.findIndex()
method comes to the rescue.
It accepts a callback function that tests that current item in the array
. The callback function accepts an argument that represents the current item in the loop. You return a truthy value when that item matches your criteria, and the method will return that index of that item.
For example, to find the index for Gandalf
in our complex array, we would do this.
// returns 1
let index = wizards.findIndex(function (wizard) {
return wizard.name === 'Gandalf';
});
⏰ Last Chance! A new session of the Vanilla JS Academy starts on Monday. Join today and get 25% off registration.
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2023-01-27T14:30:00+00:00) How to find the index of an item in an array with vanilla JavaScript. Retrieved from https://www.scien.cx/2023/01/27/how-to-find-the-index-of-an-item-in-an-array-with-vanilla-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.