Each formation contains an array of users and I want to check if one user is part of formation's users. u: the user I want to check if they are part of formation.users. This is my code
console.log(u)
console.log(formation.users)
console.log(formation.users.indexOf(u))
Which u is object and formation.users is array of objects .
This is what i see in the console
{ id: 2 }
[ User { id: 2 }, User { id: 3 } ]
-1 We see the array includes the object, why do I obtain this result? Any help please.
No, you don't see that the array includes the object, you see that the array includes an object with { id: 2 }. Unless it's the exact same object (not some other object that may or may not have the same id property as yours), it won't match:
const a = { id: 1 }
const b = { id: 1 }
const c = b
// Now there exist two objects, both with { id: 1 }.
// The first one is assigned to a, and the second
// one is assigned to both b and c. Therefore, b and c
// are equal, but a isn't equal to either of them.
console.log(a === b) // false
console.log(b === c) // true
Probably you want to check if it contains any object with a matching id instead:
console.log(formation.users.some(user => user.id === u.id))
(This is based on your question to "check if it's included" - if you actually want the index, which is what your existing code suggests that uses indexOf and not includes, then you'd have to use findIndex instead of some.)
Each object in javascript is it's own entity. So let a = {id: 1} and let b = {id: 1} in this example a and b are different objects. When you try to do the comparison match with indexOf it follows strict equality, so because they are different object it does not match them.
To achieve what you want to will need to match on one of the inner properties of user.
formation.users.findIndex((user) => user.id === u.id)