I have two arrays like this:
owners: [
{
userID: "58c4d7ac",
username: "John.Doe",
firstName: "John",
lastName: "Doe",
email: "[email protected]"
},
{
userID: "68c4d7ac",
username: "User2.Name2",
firstName: "User2",
lastName: "Name2",
email: "[email protected]"
}
]
users: [
{
userID: "58c4d7ac",
username: "John.Doe",
firstName: "John",
lastName: "Doe",
email: "[email protected]"
},
{
userID: "68c4d7ac",
username: "User2.Name2",
firstName: "User2",
lastName: "Name2",
email: "[email protected]"
},
{
userID: "88c4d7ac",
username: "User3.Name3",
firstName: "User3",
lastName: "Name3",
email: "[email protected]"
}
]
I would like to get an array of users which contains only the elements which are not in the owners array.
I tried different approaches. Finally, I ended up with the solution:
const usersItems = users.map(user => {
// Check whether the user is already an owner
if (owners.findIndex(owner => owner.userID === user.userID) === -1) {
return owner
} else {
return null;
}
});
console.log(usersItems);
// Filter out all items which are null
const newUsersItems = usersItems.filter(user => {
if (user) return user;
});
console.log(usersItems);
To me, it doesn't' look like a clean solution. Is there a cleaner and easier way to do this? As a result, I would like to have:
newUsers: [
{
userID: "88c4d7ac",
username: "User3.Name3",
firstName: "User3",
lastName: "Name3",
email: "[email protected]"
}
]