'Recoil Tutorial findIndex

In the Recoil tutorial at https://recoiljs.org/docs/basic-tutorial/atoms, they use
const index = todoList.findIndex((listItem) => listItem === item); to get the index of an object in an array. The code works but I can't replicate it, I always get a return value of -1. I thought you couldn't compare objects directly like that?
The todoList is something like:

[{id: 0, text: 'item1', isComplete: false}, {id: 1, text: 'item2', isComplete: false}]

where item is {id: 0, text: 'item1', isComplete: false}



Solution 1:[1]

They are used logic like this:

const a = {};
const b = [];
b.push(a);
b.findIndex(el=>el===a); // 0

if you defined list by your own:

[{id: 0, text: 'item1', isComplete: false}, {id: 1, text: 'item2', isComplete: false}]

you should use id || text || isComplete to find index, because you don't have a link to the object that you want to find. More about object comparision https://dmitripavlutin.com/how-to-compare-objects-in-javascript/

Solution 2:[2]

You're imagining that the === is comparing the object by value, when in fact it is comparing them by reference, see below.

const todoList = [];

const item = {id: 0, text: 'item1', isComplete: false};
todoList.push(item);

// Attempt by reference, 0
console.log(todoList.findIndex((listItem) => listItem === item));

// Attempt by value, -1
console.log(todoList.findIndex((listItem) => listItem === {id: 0, text: 'item1', isComplete: false}));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andriy
Solution 2 maraaaaaaaa