Javascript sort custom comparator function - sorting a sorted array

前端 未结 5 651
你的背包
你的背包 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 22:56

    Or as simple oneliner for first and second priority sort, you can expand it further as you wish, just replace the 0 with another comparison chain. Switch < and > or -1 and 1 for the reversed order.

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

提交回复
热议问题