Reputation: 438
I know the header is way too complicated but that's how it is right now. Let me make it more clear for you.
There is an object like
const users= [
{
id:"1",
name:"John",
mail:"[email protected]",
},
{
id:"2",
name:"Joe",
mail:"[email protected]",
},
]
Then there is
const attendingUsers = [
{
id:"1",
name:"John",
mail:"[email protected]",
.....
},
{
id:"2",
name:"Joe",
mail:"[email protected]",
.....
},}
]
Both of the arrays has different properties and I just want to get the ones that are important to me. What I need is to look through users
array and find the ones that has the same ids as the ones from attendingUsers
.
I have came up with users.filter(user => user.id == attendingUsers.map(attendingUser => attendingUser.id));
but that is simply returning empty array. Any idea what would be the best way to tackle this sort of a problem?
Upvotes: 3
Views: 5066
Reputation: 30675
We can use Array.map to create a new array of users, with a property isAttending added to each user.
We determine if they are attending by using Array.some to search for any matching attendee with the same id.
const users = [
{
id:1,
name:"John",
mail:"[email protected]",
},
{
id:2,
name:"Joe",
mail:"[email protected]",
},
{
id:3,
name:"Alice",
mail:"[email protected]",
}
]
const attendingUsers = [
{
id:"1",
name:"John",
mail:"[email protected]",
},
{
id:"2",
name:"Joe",
mail:"[email protected]",
}
]
const result = users.map(user => {
return { ...user, isAttending: attendingUsers.some(({id}) => id == user.id) };
});
console.log("Users (with attending property):", result);
Upvotes: 2
Reputation: 558
First off, you'll have to make sure if the ID types are correct. Users has Number type for IDs but attendingUsers has String type.
Let's say they're both the same type for the code below (I'm going with string).
You can turn the attendingUsers array into an array of strings with:
const attendingUsersIds = attendingUsers.map(attendingUser => attendingUser.id)
Then match the ids with:
const matchedUsers = users.filter(user => attendingUsersIds.includes(user.id))
If they're intended to not be the same type, you can use user.id.toString()
to turn the Number into a String or parseInt(attendingUser.id)
to turn the String into a Number.
Upvotes: 4