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

前端 未结 8 592
滥情空心
滥情空心 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:31

    I stepped in this problem and solved it with a simple .sort

    Assuming that your list to be sorted is stored in the variable needSort and the list with the order is in the variable order and the both are in the same scope you can run a .sort like this:

    needSort.sort(function(a,b){
      return order.indexOf(a.id) - order.indexOf(b.id);
    });
    

    It worked for me, hope it helps.

提交回复
热议问题