I have two arrays, one containings some items, and another containings sorted ids of those items like so:
const items = [
{ id: 1, label: 'foo' },
{ id: 2, label: 'bar' },
{ id: 3, label: 'lorem' },
{ id: 4, label: 'ipsum' },
]
const sortedItemIds = [4, 3, 2, 1]
I want to have another array containing items sorted by their id like so:
const sortedItems = [
{ id: 4, label: 'ipsum' },
{ id: 3, label: 'lorem' },
{ id: 2, label: 'bar' },
{ id: 1, label: 'foo' },
]
Note that the order may not be whatever, not asc
or desc
I made this piece of code, that works pretty well as it:
let sortedItems = []
sortedItemIds.map((itemId, index) => {
items.map(item) => {
if (item.id === itemId) {
sortedItems[index] = item
}
}
})
I feel like I may run into issues with a large array of items, due to the nested Array.map()
functions
Is there a better way / best practice for this scenario?