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
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
Share Improve this question asked Mar 28, 2018 at 15:04 Louis LecocqLouis Lecocq 1,8143 gold badges18 silver badges40 bronze badges 1- 1 how do you define "best way" – zfrisch Commented Mar 28, 2018 at 15:05
3 Answers
Reset to default 8You 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);
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);
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);