Skip to main content Accessibility Feedback

Arrays

Array.prototype.findIndex()

Find the index of an item in a multidimensional array (an array whose items include other arrays or objects).

Pass a callback function into the Array.prototype.findIndex() method. The callback itself accepts three arguments: the current item in the loop, the index of the current item in the loop, and the array itself. All three are optional, and you can name them anything you want.

Inside the callback, you can check some conditions about the current item. The Array.prototype.findIndex() method will return the index of the first item that you return true for.

let sandwiches = [
	{
		name: 'turkey',
		smelly: false
	},
	{
		name: 'tuna',
		smelly: true
	},
	{
		name: 'pb&j',
		smelly: false
	}
];

// Find the index of the tuna sandwich
// returns 1
sandwiches.findIndex(function (sandwich) {
	if (sandwich.name === 'tuna') {
		return true;
	}
});

Preorder my new course on Web Components! Want to learn how to build Web Components from scratch, master best practices, and more? Preorder today and get $100 off of the launch price.


Find this useful? You can support my work by purchasing an annual membership.