Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

How to find array index of an element in JavaScript

Programming Bytes

What is the findIndex method?

We can use the findIndex method to return the first index of the element that fulfills the test function.

Example:

let names = ["Vinith", "Kamal", "Ram", "Raj"];

let index = names.findIndex( (name) => {
   return name.length < 4;
});
console.log(index);

The above code will loop through each name and check if the name satisfies the test function, in our case, it will check if the name length is less than 4.

Syntax:

array.findIndex(callback, [thisArg]);

callback is the test function – it takes the following 3 arguments:

  • current_Element
  • current_Index
  • original_Array
let names = ["Vinith", "Kamal", "Ram", "Raj"];

let index = names.findIndex( (name, index, array) => {
   console.log(name, index, array);
   return name.length < 4;
});
index;

The above function will print the name, index, and array for each name in the names array until it finds the name with a length less than 4.


If no single element satisfies the test function, findIndex method will return -1.

let names = ["Vinith", "Kamal"];

let index = names.findIndex( (name, index, array) => {
   console.log(name, index, array);
   return name.length < 4;
});
index;

Alternatively, you can use the find method to get the first element value of the array that fulfills the test function.

let names = ["Vinith", "Kamal", "Ram", "Raj"];

let name = names.findIndex( (name, index, array) => {
   console.log(name, index, array);
   return name.length < 4;
});
name;

RELATED TAGS

javascript
communitycreator
RELATED COURSES

View all Courses

Keep Exploring