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

前端 未结 8 591
滥情空心
滥情空心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 13:36

    You can do it with Alasql library with simple SELECT JOIN of two arrays.

    The only one thing: Alasql understands source data as array of arrays or array of objects, so you need to convert simple array to array of arrays (see Step 1)

    var data1 = [ { id: 3, name:'jess' }, { id: 1, name:'abc' }, 
       { id: 9, name:'...' }, { id: 4, name:'alex' } ];
    var data2 = [3, 1, 9, 4];
    
    // Step 1: Convert [3,1,9,4] to [[3],[1],[9],[4]]
    var data2a = data2.map(function(d){return [d]});
    
    // Step 2: Get the answer
    var res = alasql('SELECT data1.* FROM ? data1 JOIN ? data2 ON data1.id = data2.[0]',
        [data1,data2a]);
    

    Try this example at jsFiddle.

提交回复
热议问题