Reputation: 2867
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?
Upvotes: 0
Views: 47
Reputation: 122047
You could create one object where keys are ids and then use that object get values by id.
const items = [{ id: 1, label: 'foo' },{ id: 2, label: 'bar' },{ id: 3, label: 'lorem' },{ id: 4, label: 'ipsum' }]
const sortedItemIds = [4, 3, 2, 1]
const obj = {}
items.forEach(o => obj[o.id] = o);
const sortedItems = sortedItemIds.map(e => Object.assign({}, obj[e]));
console.log(sortedItems)
Upvotes: 3
Reputation: 33726
You don't need the function map for doing this, just use the find Array.indexOf
and Array.sort
in order to sort it.
const items = [{ id: 1, label: 'foo' },{ id: 2, label: 'bar' },{ id: 3, label: 'lorem' },{ id: 4, label: 'ipsum' }],
sortedItemIds = [4, 3, 2, 1];
items.sort((a, b) => sortedItemIds.indexOf(a.id) - sortedItemIds.indexOf(b.id));
console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1