Array.findIndex()
is a method in JavaScript that returns the index of a first array element that satisfies the provided condition; otherwise, if no such element exists, it returns -1. This method was first introduced to JavaScript with ES6.
Note that Array.findIndex()
does not execute the function for array elements without values, nor does it change the original array.
array.findIndex(function(valueToBeFound, index, arr), thisValue)
const cities = ["Paris", "Barcelona", "New York", "Moscow"]function getCity(city) {return city === "New York";}console.log(cities.findIndex(getCity)) // 2
const lunch = ["Pizza", "Lasagna", "Pumpkin Pie", "Steak"]function getFood(meal) {return meal === "Spaghetti";}console.log(lunch.findIndex(getFood)) // returns index -1 since Spaghetti is not found in the lunch array
Array.findIndex()
using arrow functionBy using the arrow function introduced with ES6, the syntax of this method can be simplified even further, as shown in the following example:
const videoGames = ["Dragon Age: Inquisition", "Mass Effect 3", "Greedfall", "The Witcher 3"];const index = videoGames.findIndex(game => game === "Mass Effect 3");console.log(index); // 1console.log(videoGames[index]); // "Mass Effect 3"