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;
	}
});

Join the Lean Web Club! Coaching. Courses. Coding resources. Get the skills, confidence, and support you need to learn front-end web development and achieve long-term success.


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