Skip to content Skip to sidebar Skip to footer

Sorting Multiple Javascript Array

I have created this script with the help of the Haversine formula, the problem is that it keeps directing me to the first location on the array, no matter how many time I swap them

Solution 1:

You're not sorting the array of locations, only the array of distances.

You should drop the distance into the locations array (i.e. as the fourth member of each element):

for(var i = 0; i < locations.length; ++i) {
    var l = locations[i];
    l[3] = haversine(userLatitude, userLongitude, l[1], l[2]);
}

and then use a "comparator" function that looks at that distance field:

locations.sort(function(a, b) {
    return (a[3] < b[3]) ? -1 : ((a[3] > b[3]) ? 1 : 0);
});

Post a Comment for "Sorting Multiple Javascript Array"