Javascript sort custom comparator function - sorting a sorted array

前端 未结 5 665
你的背包
你的背包 2021-02-03 22:23

I have an array of objects of the following form:

arr[0] = { \'item1\' : 1234, \'item2\' : \'a string\' };

I sort it first by \'item1\'

5条回答
  •  庸人自扰
    2021-02-03 23:02

    You can have four different comparison functions - one sorting by item1, one by item2, one by item1 then item2 and one by item2 then item1.

    E.g.:

    arr.sort(function(a,b){
      if(a.item1 == b.item1){
        return a.item2 > b.item2 ? 1 : a.item2 < b.item2 ? -1 : 0;
      }
    
      return a.item1 > b.item1 ? 1 : -1;
    });
    

提交回复
热议问题