I have 2 object arrays (allUsers and friendsOnTrip). Both these arrays are of the same format. Each object within them contains details of a user (i.e. firstName and lastName). I am trying to make it that if an object in one array is not in the other one, then push that object to a new array, otherwise don't.
allUsers.forEach((user) => { if (friendsOnTrip.indexOf(user) <= -1) { this._friendsNotOnTrip.push(user); } }); The problem is that even if the object user seems like it is in friendsOnTrip, then the expression of:
if (friendsOnTrip.indexOf(user) <= -1) ...will still evaluate to true (which is wrong) so I end up with objects within this._friendsNotOnTrip that shouldn't be there.
An example of one of the objects:
{ email: "[email protected]", firstName: "foo", lastName: "bar", key: "123456789", friends: [ "987654321", "246808642" ], location: { lng: -1.24567, lat: 50.9865 }, usersToSeeLocation: [ "987654321" ] } The object at position 0 in allUsers and the object at position 0 in friendsOnTrip are the same object. I tested the individual attributes and got the following results:
console.log(allUsers[0].firstName === friendsOnTrip[0].firstName); //true console.log(allUsers[0].lastName === friendsOnTrip[0].lastName); //true console.log(allUsers[0].email === friendsOnTrip[0].email); //true console.log(allUsers[0].friends === friendsOnTrip[0].friends); //false console.log(allUsers[0].key === friendsOnTrip[0].key); //true console.log(allUsers[0].location === friendsOnTrip[0].location); //false console.log(allUsers[0].usersToSeeLocation === friendsOnTrip[0].usersToSeeLocation); //false console.log(allUsers[0] === friendsOnTrip[0]); //false Looking inside friends, usersToSeeLocation, and location in both allUsers[0] and friendsOnTrip[0], the contents are the exact same so I am unsure as to why those expressions are evaluating to false.
Objectshave same keys as well as values?? If so then you can try with JSON.stringify both the Objects and then compare. If both theObjectshave same key but having different values then It must bereturnfalse.