在最近的一个项目中使用到了js排序。在以前都是对单个属性进行排序的,但是这次是要对一个对象的属性进行排序。

 在项目中我需要对返回的距离进行升序。代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
for  ( var  k = 0,
l = data.length; k < l; k++) {
     //获取距离
     var  lat = data[k].lat;
     var  lng = data[k].lng;
     var  map =  new  BMap.Map();
     //Memory.GetValue("Longitude")Memory.GetValue("Latitude");
     var  pointB =  new  BMap.Point(lat, lng);
     var  distances = map.getDistance(pointA, pointB);
     if  (distances == 0) {
         //datas = detailDatas.replace('@100',0);
     else  {
         var  _t = distances.toString().indexOf( '.' );
         _d = distances.toString().substring(0, _t);
     }
     data[k].distance = _d;
}
data.sort( function (o1, o2) {
     return  o1.distance - o2.distance;
});

我觉得我有必要对代码进行说明:

我得到的数据是一个json的list,使用百度提供的接口对坐标之间的举例进行排序。data[k].distance = _d;这行代码是向js对象新增一个距离的属性。

核心代码:

1
2
3
data.sort( function (o1, o2) {
     return  o1.distance - o2.distance;
});

是根据距离进行升序。如果需要降序可以改为:

1
2
3
data.sort( function (o1, o2) {
     return  o2.distance - o1.distance;
});

普通数组的的排序也是类似的,如下示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function  compare(arg1,arg2){
     var  tmp1=parseInt(arg1);
     var  tmp2=parseInt(arg2);
     if (tmp1<tmp2){
         return  -1;
     } else  if (tmp1==tmp2){
         return  0;
     } else {
         return  1;
     }
}
var  arr= new  Array(1,3,11,22,54,9);
alert(arr.sort());
alert(arr.sort(compare));