I have a list of objects:
[ { id: 4, name:\'alex\' }, { id: 3, name:\'jess\' }, { id: 9, name:\'...\' }, { id: 1, name:\'abc\' } ]
I have a
How I solved pretty much the same issue
data = [{ id: 4, name:'alex' }, { id: 3, name:'jess' }, { id: 9, name:'...' }, { id: 1, name:'abc' } ];
sorted = [3, 1, 9, 4].map((i) => data.find((o) => o.id === i));
A little something like this:
var data = [ { id: 4, name:'alex' }, { id: 3, name:'jess' }, { id: 9, name:'...' }, { id: 1, name:'abc' } ],
order = [ 3, 1, 9, 4],
sorted = [],
items = {},
i;
for (i = 0; i < data.length; i++)
items[data[i].id] = data[i];
for (i = 0; i < order.length; i++)
sorted.push(items[order[i]]);
The idea is to put the items from data
into an object using the ids as property names - that way you can retrieve the item with a given id without without having to search through the array. (Otherwise you'd have to use a nested loop, or the Array.indexOf()
function inside a single loop which is effectively going to be a nested loop as far as performance.)
This assumes that no two elements in data
have the same id property.