How to sort an array of objects by multiple fields?

后端 未结 30 2332
北恋
北恋 2020-11-21 11:34

From this original question, how would I apply a sort on multiple fields?

Using this slightly adapted structure, how would I sort city (ascending) & then price (

30条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 12:04

    Sorting on two date fields and a numeric field example:

    var generic_date =  new Date(2070, 1, 1);
    checkDate = function(date) {
      return Date.parse(date) ? new Date(date): generic_date;
    }
    
    function sortData() {  
      data.sort(function(a,b){
        var deltaEnd = checkDate(b.end) - checkDate(a.end);
        if(deltaEnd) return deltaEnd;
    
        var deltaRank = a.rank - b.rank;
        if (deltaRank) return deltaRank;
    
        var deltaStart = checkDate(b.start) - checkDate(a.start);
        if(deltaStart) return deltaStart;
    
        return 0;
      });
    }
    

    http://jsfiddle.net/hcWgf/57/

提交回复
热议问题