Here is a JSON array I am working with:
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'
},
];
Within this array, there is a dynamic variable called details['distance']
, which is calculated using the Haversine formula in the function getDistance()
.
var dist = getDistance(lt,lg,lat,lng);
details[i]['distance'] = dist;
The information from this array is displayed within a div, and I want to sort the list by distance.
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/>';
}
My sorting implementation looks like this:
details.sort(function(a,b) { return parseFloat(a.distance) - parseFloat(b.distance) } );
Although this sorts the values by distance, it sometimes displays incorrect details such as address and type after sorting. The entire array needs to be sorted without mixing up the other details.