Js 数组排序【支持对象】
程序员文章站
2022-06-17 15:09:35
...
//兼容 IE&FF&Safari
var format=(arr,type,keys){
switch (type){
case 0:return arr.sort(function(a,b){a=(keys)?(a[keys])?a[keys]:a:a;b=(keys)?(b[keys])?b[keys]:b:b; return a>b?-1:(a>b)?0:1; }); break;
case 1:return arr.sort(function(a,b){a=(keys)?(a[keys])?a[keys]:a:a;b=(keys)?(b[keys])?b[keys]:b:b; return a<b?-1:(a<b)?0:1; }); break;
default:return arr.sort(function(a,b){a=(keys)?(a[keys])?a[keys]:a:a;b=(keys)?(b[keys])?b[keys]:b:b; return a>b?-1:(a>b)?0:1; }); break;
}
}
var sample=[2,1,6,4,48];
format(sample,0);//从大到小 [48,6,4,2,1]
format(sample,1);//从小到大 [1,2,4,6,48]
var responseData=[{"region":"主院","title":1,"datetime":"2009-08-10 10:23:35","mode":"发表"},
{"region":"城市","title":4,"datetime":"2009-08-10 10:23:32","mode":"发表"},
{"region":"别院","title":3,"datetime":"2009-08-10 10:23:33","mode":"回复"},
{"region":"主院","title":2,"datetime":"2009-08-10 10:23:34","mode":"发表"},
{"region":"城市","title":5,"datetime":"2009-08-10 10:23:31","mode":"回复"}
];
format(responseData,0,'datetime');//根据【datetime】从大到小排序
format(sample,1,'datetime');//根据【datetime】从小到大排序
上一篇: 冒泡事件的移除以及获取事件源