My current setup involves a collection of objects structured like this:
const items = [
{
name: 'book',
id: 3
},
{
name: 'pen',
id: 1
},
{
name: 'paper',
id: 5
}
];
I also have an array of Ids:
const ids = [1, 5];
What I want to achieve is to extract all the "items" that match any of the ids in my list, resulting in this:
const result = [
{
name: 'pen',
id: 1
},
{
name: 'paper',
id: 5
}
]
I currently use a method where I iterate through each id and check for matches in the items:
let result = [];
for (let i = 0; i < ids.length; i += 1) {
const foundItem = items.find(x => x.id === ids[i]);
result.push(foundItem);
}
However, considering that my actual dataset can be quite large with thousands of entries and the list of ids could also be extensive, I'm curious if this approach is the most efficient one or if there's a better way to accomplish the same goal.
Is there a more optimized way to map these results?