I have a list of objects that say look something like this:
const fruit = [
{
name: 'banana',
id: 1
},
{
name: 'apple',
id: 8
},
{
name: 'orange',
id: 3
}
];
And I have a list of Ids:
const ids = [8, 1];
And I'm looking to grab all the "fruit" that have an id in my list of ids, i.e. I want my result to look like:
const result = [
{
name: 'apple',
id: 8
},
{
name: 'banana',
id: 1
}
]
I have a "working" solution where I basically go:
let result = [];
for (let i = 0; i < ids.length; i += 1) {
const foundFruit = fruit.find(x => x.id === ids[i]);
result.push(foundFruit);
}
But ultimately I'm wondering if this is the most efficient way to do this, as in my real example, my list of fruit can potentially be thousands of fruit long, and I could similarly ALSO have a huge list of ids.
Would this approach be the best or is there a more efficient way of mapping these results?
fruitMap = new Map(fruit.map(f => [f.id, f]))and thenresult = ids.map(id => fruitMap.get(id))