How do I sort an array of objects based on the ordering of another array?

前端 未结 8 583
滥情空心
滥情空心 2020-11-28 12:41

I have a list of objects:

[ { id: 4, name:\'alex\' }, { id: 3, name:\'jess\' }, { id: 9, name:\'...\' }, { id: 1, name:\'abc\' } ]

I have a

8条回答
  •  清歌不尽
    2020-11-28 13:45

    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.

提交回复
热议问题