graffixnyc graffixnyc - 1 month ago 9
Node.js Question

Filter an Array based on multiple values

I have the following simple JSON array:

const personList = [
{
id: 1,
name: "Phil"
},
{
id: 2,
name: "Bren"
},
{
id: 3,
name: "Francis Underwood"
},
{
id: 4,
name: "Claire Underwood"
},
{
id: 5,
name: "Ricky Underwood"
},
{
id: 6,
name: "Leo Boykewich"
}
];


And I would like to filter this by passing an array of ids so something like [1,4] would be passed in and it would only return "Phill" and "Claire Underwood"

This is what the function looks like but I know it's wrong attendeeIds is an array that's passed in [1, 4]:

getAttendeesForEvent: (attendeeIds) => {
if (attendeeIds === undefined) return Promise.reject("No attendee id provided");

return Promise.resolve(personList.filter(x => x.id == [attendeeIds]).shift());
}


I haven't used JS in years. I've looked for examples but they all seem too complex for what I'm trying to achieve. So how can I filter this based on an array of id's passed in?

Answer
return Promise.resolve(personList.filter(x => attendeeIds.indexOf(x.id) !== -1));

You want to check if the id of each item your looping over exists inside of attendeeIds. Use Array.indexOf inside of the filter to do that.

This will return an array of { id: #, name: String } objects.

If you want to return just the names of those objects, you can do a map afterwards which will transform an array into another array using the function that you provide.

const filteredNames = personList
    .filter(x => attendeeIds.indexOf(x.id) !== -1)
    .map(x => x.name);
// ['Phil', 'Claire Underwood']
Comments