按距离排序对象数组

时间:2015-05-13 11:23:00

标签: javascript arrays json google-maps sorting

我有一个JSON数组:

var details = [
{
    'address':'Pantaloons,701-704, 7th Floor, Skyline Icon Business Park, 86-92 Off A. K. Road,Marol Village, Andheri East,Mumbai, Maharashtra 400059',
    'lat':'19.099910',
    'lng':'72.915373',
    'time':'NA',
    'sex':'Unisex',
    'place':'mall'
    },
    {
    'address':'Garodia Shopping Centre,Ghatkopar East,Mumbai, Maharashtra 400077',
    'lat':'19.074185',
    'lng':'72.908169',
    'time':'NA',
    'sex':'Male',
    'place':'mall'
    },
    {
    'address':'EF Mall,Andheri,Rambaug, MHADA Colony 20, Powai,Mumbai, Maharashtra 400076',
    'lat':'19.119056',
    'lng':'72.901324',
    'time':'NA',
    'sex':'Male',
    'place':'mall'
    },
];

也有动态变量details.['distance']。此处getDistance()haversine formula

var dist = getDistance(lt,lg,lat,lng);
details[i]['distance'] = dist;

列表中的所有这些值都显示在div中,我想按距离对列表进行排序。

for (i = 0; i < details.length; i++) {
    var add= details[i].address;
    var lat = details[i].lat;
    var lng = details[i].lng;
    var time = details[i].time;
    var latLng = new google.maps.LatLng(lat, lng);
    var Gender = details[i].sex;
    var type = details[i].place;
    var dist = getDistance(lt,lg,lat,lng);
    details[i]['distance'] = dist;
    document.getElementById('list').innerHTML +='<p><img src="'+type+'.png" style="float:left;margin-right:5;"><div id="address"> ' + add +'</div><br><img style="height:30;float:right;" src="'+Gender+'.png" title="+Gender+"><a class="review" href="#">See Reviews</a>'+'<img style="float:right;margin-top:6;" src="write.png" title="Write a Review"><div id="time">Timings:'+ time +'</div>'+details[i].distance +'km'+'</p><hr/>';

    }

我的实施如下

details.sort(function(a,b) { return parseFloat(a.distance) - parseFloat(b.distance) } );

然而,这只按距离对值进行排序,并显示列表的其他值,就像address,type一样(即它显示了排序后其他地址到另一个地址的距离)。整个数组必须得到排序没有错误的细节。

2 个答案:

答案 0 :(得分:3)

var objs = [ 
        { first_nom: 'Lazslo', last_nom: 'Jamf'     },
        { first_nom: 'Pig',    last_nom: 'Bodine'   },
        { first_nom: 'Pirate', last_nom: 'Prentice' }
    ];
for(var i=0; i<objs.length; i++){
    objs[i]['distance'] = objs[i]['last_nom'];

}
function compare(a,b) {
  if (a.distance < b.distance)
     return -1;
  if (a.distance > b.distance)
    return 1;
  return 0;
}
objs.sort(compare);
alert(JSON.stringify(objs)); 

输出:[{"first_nom":"Pig","last_nom":"Bodine","distance":"Bodine"},{"first_nom":"Lazslo","last_nom":"Jamf","distance":"Jamf"},{"first_nom":"Pirate","last_nom":"Prentice","distance":"Prentice"}]

<强> DEMO

答案 1 :(得分:0)

回答你的问题有点困难,因为你的数组中没有像birdspider所指出的距离属性。无论如何,你的方法应该有效。您可以在控制台中测试它。

var details = [{'distance':'24.1','b':99},{'distance':'-12.5','b':100},{'distance':'35.6','b':101}]
details.sort(function(a,b) { return parseFloat(a.distance) - parseFloat(b.distance) } )

现在再次检查详细信息变量,您将看到:

[{'distance':'-12.5','b':100},{'distance':'24.1','b':99},{'distance':'35.6','b':101}]