Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
es6
findindex
array
community creator

Array.findIndex() in ES6

Silvija Prozinger

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.

Syntax

array.findIndex(function(valueToBeFound, index, arr), thisValue)
  • valueToBeFound - required value, it represents the value we want to find in the array
  • index - optional value, represents the array index of the current element
  • arr - optional value, represents the array object the current element belongs to
  • thisValue - optional value to be passed to the function to be used as its “this” value. If this parameter is empty, the value “undefined” will be passed as its “this” value

Examples

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 function

By 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); // 1
console.log(videoGames[index]); // "Mass Effect 3"

RELATED TAGS

javascript
es6
findindex
array
community creator
RELATED COURSES

View all Courses

Keep Exploring