Q: Retrieve several items from a list by ids I have an array such as :
const cars = [
  { id: 23423, brand: 'bmw', doors: 2, color: 'red' },
  { id: 23452, brand: 'volvo', doors: 4, color: 'gray' },
  { id: 97456, brand: 'citroen', doors: 4, color: 'black' },
  { id: 45784, brand: 'dodge', doors: 2, color: 'red' },
  { id: 23452, brand: 'ferrari', doors: 2, color: 'red' },
  { id: 23522, brand: 'bmw', doors: 2, color: 'blue' }
];

Here i have a list of ids such as : [45784, 23522]
I'd like to find the best way using map, filter or reduce to retrieve the items in the first array using the ids array.
Thanks

A: Simple as:


const 
  cars = [
  { id: 23423, brand: 'bmw', doors: 2, color: 'red' },
  { id: 23452, brand: 'volvo', doors: 4, color: 'gray' },
  { id: 97456, brand: 'citroen', doors: 4, color: 'black' },
  { id: 45784, brand: 'dodge', doors: 2, color: 'red' },
  { id: 23452, brand: 'ferrari', doors: 2, color: 'red' },
  { id: 23522, brand: 'bmw', doors: 2, color: 'blue' }
],
  ids = [45784, 23522];

let arr = cars.filter(elem => ids.includes(elem.id));

console.log(arr);



A: You could filter by using Array#includes.
This proposal uses a destructuring assignment for the id property of the object.


var cars = [{ id: 23423, brand: 'bmw', doors: 2, color: 'red' }, { id: 23452, brand: 'volvo', doors: 4, color: 'gray' }, { id: 97456, brand: 'citroen', doors: 4, color: 'black' }, { id: 45784, brand: 'dodge', doors: 2, color: 'red' }, { id: 23452, brand: 'ferrari', doors: 2, color: 'red' }, { id: 23522, brand: 'bmw', doors: 2, color: 'blue' }],
    ids = [45784, 23522],
    result = cars.filter(({ id }) => ids.includes(id));

console.log(result);



A: Convert a Set from the ids array, and use Array.filter() to take only items that exist in the Set:


const cars = [
  { id: 23423, brand: 'bmw', doors: 2, color: 'red' },
  { id: 23452, brand: 'volvo', doors: 4, color: 'gray' },
  { id: 97456, brand: 'citroen', doors: 4, color: 'black' },
  { id: 45784, brand: 'dodge', doors: 2, color: 'red' },
  { id: 23452, brand: 'ferrari', doors: 2, color: 'red' },
  { id: 23522, brand: 'bmw', doors: 2, color: 'blue' }
];

const ids = [45784, 23522];

const idsSet = new Set(ids);
const result = cars.filter(({ id }) => idsSet.has(id));

console.log(result);


