findIndex() Method in JavaScript

JavaScript
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 method in JavaScript is used to find the index of the first element that matches a specific condition.
  • It is similar to the method, but instead of returning the element itself, it returns the index of that element.
  • If no element satisfies the condition, returns .

How 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 .

Example:

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

Using findIndex() to Locate a Blog by ID:

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

Here:

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

Checking the Index:

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

Displaying the Blog:

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

Output:

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

Summary:

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