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