3

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"}

asked Dec 5, 2020 at 13:56

2 Answers 2

1

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);

answered Dec 5, 2020 at 13:57

5 Comments

@taslimkd what's the issue?
i can not explain it here how can i sent picture here
I have included photo , you can understand the issue now..
You need to convert the ObjectId to a String when comparing, something like: e._id.toString(). You can research this more depending on the technology you're using
@taslimkd Have you logged both values? Is the actually within the array? Or is it showing -1 because there is no element containing the provided id? You can implicitly convert values by using == instead of ===, so no reason to call toString().
0

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);
answered Dec 5, 2020 at 15:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.