findIndex() Method in JavaScript

JavaScript2 min read
findIndex() Method in JavaScript
javascriptfindindex methodarray methods

The findIndex() method in JavaScript is used to find the index of the first element that matches a specific condition.

findIndex() Method in JavaScript

  • The findIndex() method in JavaScript is used to find the index of the first element that matches a specific condition.
  • It is similar to the find() method, but instead of returning the element itself, it returns the index of that element.
  • If no element satisfies the condition, findIndex() returns -1.

How findIndex() Works:

  • The method takes a callback function that is executed for each element.
  • If the condition is satisfied, it returns the index of the first matching element.
  • If no match is found, it returns -1.

Example:

  • We have a blogs array containing some blog posts with id, title, and description:
const blogs = [ { id: 1, title: 'Title-1', description: 'Description-1' }, { id: 2, title: 'Title-2', description: 'Description-2' }, { id: 3, title: 'Title-3', description: 'Description-3' } ];

Using findIndex() to Locate a Blog by ID:

  • We want to find the blog with id = 2 using findIndex().
function foundBlog(blogId) { return blogs.findIndex(blog => blog.id === blogId); }

Here:

  • The findIndex() method iterates over the blogs array to locate the first blog with the matching id (in this case, id: 2).
  • The index of the blog is returned by the function.

Checking the Index:

  • We store the result of the function in foundIndex:
const foundIndex = foundBlog(2);

Displaying the Blog:

  • We check if the index is not -1, which means the blog was found. If found, we print the blog details, otherwise, we display "Blog not found":
if (foundIndex !== -1) { document.write(` Title: ${blogs[foundIndex].title}, <br> Description: ${blogs[foundIndex].description} `); } else { document.write("Blog not found!"); }

Output:

  • If the blog is found, the output will be:
Title: Title-2, Description: Description-2
  • If no matching blog is found:
Blog not found!

Summary:

  • The findIndex() method is useful for finding the index of an element based on a condition.
  • It returns -1 if no matching element is found.
  • The method is ideal when you need the position of an element, rather than the element itself.