0

i have this

arr = [{name: 'pippo',lastname: 'p'},{name: 'mickey',lastname: 'mouse'}]
x ={name: 'mickey', lastname: 'mouse'}
arr.indexOf(x)

why arr.indexOf(x) returning -1? Is there another solution to find the index of an object inside of an array of objects?

3 Answers 3

5

Since you have array of objects, it does not work straight forward using indexOf() to get the index of that specific object in that array. You need to use findIndex() so that when there is a matching object in the array, it returns the respective index of that object, else -1.

arr = [{name: 'pippo',lastname: 'p'},{name: 'mickey',lastname: 'mouse'}]
x ={name: 'mickey', lastname: 'mouse'}
console.log(arr.findIndex((obj) => obj.name == x.name && obj.lastname === x.lastname));

Sign up to request clarification or add additional context in comments.

1 Comment

@RaydenC you can tick mark the answer if that was helpful to you. Glad to help :)
1

indexOf() checks the reference of the object inside the array. Since you are making a new object and passing it as an argument to indexOf() it doesn't match the reference of object inside the array so it fails.

let arr = [{name: 'pippo',lastname: 'p'},{name: 'mickey',lastname: 'mouse'}]
arr.indexOf(arr[1])

Whereas this code will return 1 as expected as the reference is same.

Solution as given by @Ankit

arr = [{name: 'pippo',lastname: 'p'},{name: 'mickey',lastname: 'mouse'}]
x ={name: 'mickey', lastname: 'mouse'}
console.log(arr.findIndex((obj) => obj.name == x.name && obj.lastname === x.lastname));

Comments

0

Using simple loop

arr = [{name: 'pippo',lastname: 'p'},{name: 'mickey',lastname: 'mouse'}]
x ={name: 'mickey', lastname: 'mouse'}


for(let i=0;i< arr.length;i++){
  if(JSON.stringify(arr[i])===JSON.stringify(x))
   console.log(i)
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.