Skip to main content Accessibility Feedback

How to get the index of an object in an array with vanilla JS

The Array.indexOf() method returns the index of the first matching item in an array (or -1 if it doesn’t exist).

var wizards = ['Gandalf', 'Radagast', 'Saruman', 'Alatar'];

// Returns 1
wizards.indexOf('Radagast');

But… that doesn’t work if the array contains objects instead of simple strings or numbers.

var wizards = [
	{
		name: 'Saruman',
		color: 'white'
	},
	{
		name: 'Gandalf',
		color: 'gray'
	},
	{
		name: 'Radagast',
		color: 'brown'
	},
	{
		name: 'Alatar',
		color: 'blue'
	},
	{
		name: 'Pallando',
		color: 'blue'
	}
];

// returns -1
wizards.indexOf({
	name: 'Radagast',
	color: 'brown'
});

Fortunately, ES6 introduced a new method that does exactly what we want: Array.findIndex().

The Array.findIndex() method

The Array.findIndex() method works a lot like some of the other new ES6 array methods.

You call it on the array you want to search in, and pass in a callback function as an argument. The callback function accepts three arguments: the current item in the array, the item’s index, and the array itself. All three are optional.

The callback argument should return true when the item you’re looking for is found. Array.findIndex() will return that items index (or -1 if it’s not found).

Looking at our complex array again, we would do this.

// returns 2
wizards.findIndex(function (wizard) {
	return wizard.name === 'Radagast';
});

Here’s a demo.

Browser compatibility

The Array.findIndex() method works in all modern browsers, but not IE. You can push support back to IE6 with a polyfill.