Matching a set of objects within an array based on a different array of search property values in Javascript

Viewed 48

Is there a nicer way to filter an object array based on a set of possible values for a particular property?

This works but seems a bit clunky.

const all = [
  {id: 1}, {id: 2}, {id: 3} ...
]
const ids = [2, 3];

const selected = (all, ids) =>
  all.filter(obj => ids.map(id => id === obj.id).some(match => match));

selected(all, ids);
// [{id: 2}, {id: 3}]

In Python it'd be something like this:

selected = [obj for obj in all if obj.id in ids]
3 Answers

You can simply filter out the array using Array.filter() and Array.includes():

const all = [ {id: 1}, {id: 2}, {id: 3} ];
const ids = [2, 3];

const selected = (all, ids) => all.filter(obj => ids.includes(obj.id));
  
console.log(selected(all,ids));

You can use of Array.filter, object destructuration and Array.includes, like :

const all = [{
  id: 1,
}, {
  id: 2,
}, {
  id: 3,
}];

const ids = [
  2,
  3,
];

const selected = (all, ids) => all.filter(({
  id,
}) => ids.includes(id));

console.log(selected(all, ids));
// [{id: 2}, {id: 3}]

You could take a Set for the wanted id and check against for filtering.

const
    all = [{ id: 1 }, { id: 2 }, { id: 3 }],
    ids = [2, 3],
    result = all.filter((s => ({ id }) => s.has(id))(new Set(ids)));

console.log(result);

Related