Sort an array of objects based on another array of ids

后端 未结 10 2133
故里飘歌
故里飘歌 2020-11-28 16:27

I have 2 arrays

a = [2,3,1,4]
b = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]

How do I get b sorted based on a? My desir

10条回答
  •  伪装坚强ぢ
    2020-11-28 17:03

    You can provide a custom comparison function to JavaScript's Array#sort method.

    Use the custom comparison function to ensure the sort order:

    var sortOrder = [2,3,1,4],
        items     = [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
    
    items.sort(function (a, b) {
      return sortOrder.indexOf(a.id) - sortOrder.indexOf(b.id);
    });
    

    MDN:

    • If compareFunction(a, b) returns less than 0, sort a to an index lower than b (i.e. a comes first).
    • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
    • If compareFunction(a, b) returns greater than 0, sort b to an index lower than a (i.e. b comes first).

提交回复
热议问题