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.

3 Answers3

0

If you want to do that, you'll need findIndex

const nonsense = [{x: '1'}];
console.log(nonsense.findIndex(item => item.x === '1')); // prints 0
Joseph Wang
  • 2,870
  • 6
  • 18
  • 44
  • Sidenote: it works if you use a variable to initiate the object. Example: `const a = {x: 1};` `const arr = [a];` `arr.indexOf(a);` – Reyno Jun 17 '20 at 10:57
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
  • 25,372
  • 4
  • 33
  • 58
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,462
  • 2
  • 23
  • 29