码迷,mamicode.com
首页 > 编程语言 > 详细

jQuery对象数组排序

时间:2017-10-20 18:29:43      阅读:428      评论:0      收藏:0      [点我收藏+]

标签:func   cti   bsp   int   方法   nbsp   对象数组   .so   时间   

如何对下列对象数组排序,要将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 ;
     })

 

jQuery对象数组排序

标签:func   cti   bsp   int   方法   nbsp   对象数组   .so   时间   

原文地址:http://www.cnblogs.com/-scl/p/7700216.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!