How to find Index Number of this array value?

Viewed 65

const options = [
{_id: "0175", name: "Ahnaf"},
{_id: "8555", name: "Abir"},
{_id: "8795", name: "Book"},
]

now how to get index of _id = 8795 ?? It means how I can get the index number to get this object {_id: "8795", name: "Book"}

2 Answers

You can use .findIndex:

const options = [
{_id: "0175", name: "Ahnaf"},
{_id: "8555", name: "Abir"},
{_id: "8795", name: "Book"},
]

const index = options.findIndex(e => e._id==="8795");

console.log(index);

You need use combination of find and findIndex to find the index you are looking for.

const options = [
  {_id: "0175", name: "Ahnaf"},
  {_id: "8555", name: "Abir"},
  {_id: "8795", name: "Book"},
  ]

const foundObj = options.find((option) => option._id === "8555")
const index = options.findIndex((option, index) => {
  if(typeof foundObj !== "undefined" && option._id === foundObj._id) {
    return index
  }else
  return null
} )

console.log('index', index);
Related