Solution

To get the index of an array element in react js, use the findIndex() method and pass your value it will search, and if the value match with any array element it will return the index of the element.

findIndex()

The findIndex() method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.

Snippet

In this snippet, we will create a sample array and find the index of specific values.

const arr = ["aguidehub", "infinitbility", "sortoutcode"];

let index = arr.findIndex((e) => e == "infinitbility");

console.log(index); // 1

Before Doing any operation using got index first check index should be greater or equal to 0 else if the value is not present in the index you will get -1 and it will cause an error.

const arr = ["aguidehub", "infinitbility", "sortoutcode"];

let index = arr.findIndex((e) => e == "infinitbility");

if (index >= 0) {
  console.log(index); // 1
}

Example

In this example, we will show the index of specific values in the console and page.

Let’s start coding…

import React, { useEffect, useState } from "react";
export default function App() {
  const [arr, setArr] = useState(["aguidehub", "infinitbility", "sortoutcode"]);

  useEffect(() => {
    console.log("Index of infinitbility", getIndex("infinitbility"));
  }, []);

  const getIndex = (value) => {
    let index = arr.findIndex((e) => e == value);

    if (index >= 0) {
      return index;
    }
    return "Element Not Exist";
  };

  return (
    <div className="App">
      <h1>{`Index of infinitbility`}</h1>
      <p>{getIndex("infinitbility")}</p>
    </div>
  );
}

Output

Array, Index

codesandbox