jQuery对象数组排序

如何对下列对象数组排序,要将weekday相同的放在一块,并按时间升序:

[
{"start":"14:01","end":"16:00","weekday":1}
{"start":"10:00","end":"12:00","weekday":0},
{"start":"14:01","end":"16:00","weekday":0},
{"start":"10:00","end":"12:00","weekday":1},
{"start":"12:01","end":"14:00","weekday":1},
{"start":"12:01","end":"14:00","weekday":0},
]

Jquery对排序提供了一个方法:sort()。但是这个只是针对string int这样的原始类型的。对对象,对象数组不行。

对对象,对象数组我们可以使用sort()的自定义方法:

数组.sort( 

  function sortRule(a,b) {
    if(a.属性 > b.属性) return 1 交换位置

    if(a.属性 < b.属性) return -1 不要交换位置

    if(a.属性 = b.属性) return 0 不要交换位置
  }

)

代码:对它进行两次排序就OK了,先根据时间排序,在根据weekday进行排序。(但是反过来先根据weekday在根据时间排序就不行)

var d = [
            {"start":"10:00","end":"12:00","weekday":0},
            {"start":"12:01","end":"14:00","weekday":0},
            {"start":"12:01","end":"14:00","weekday":1},
            {"start":"10:00","end":"12:00","weekday":1},
            {"start":"14:01","end":"16:00","weekday":1},
            {"start":"14:01","end":"16:00","weekday":0}
         ] ;
               
     d.sort(function(a,b){
            if(a.start>b.start) return 1 ;
            if(a.start<b.start) return -1 ;
            return 0 ;
     }) ;
     d.sort(function(a,b){
            if(a.weekday>b.weekday) return 1 ;
            if(a.weekday<b.weekday) return -1 ;
            return 0 ;
     })

 

posted @ 2017-10-20 16:41  孟夏草木长  阅读(6284)  评论(0编辑  收藏  举报