1
const nonsense = [{x: '1'}];
console.log(nonsense.indexOf({x: '1'})); // prints -1

I don't understand why it's printing -1 even though the specified object clearly exists in the array.

2 Answers2

0

objects are compared by their reference, not by their values.

object inside nonsense array is a different object from the object you passed to indexOf function even though they have same key-value pairs.

Following code will give you the correct index

const obj = {x: '1'};
const nonsense = [obj];

console.log(nonsense.indexOf(obj));
Yousaf
  • 27,861
  • 6
  • 44
  • 69
0

As, in javaScript the objects are compared by reference, not by the values.

const nonsense = [{x: '1'}];
console.log(nonsense.map(o => o.x).indexOf('1'));

or, probably with better performance for larger arrays:

console.log(nonsense.findIndex(o => o.x ==='1'));
solanki...
  • 4,982
  • 2
  • 27
  • 29