排序多个JavaScript数组 [英] Sorting multiple JavaScript array

查看:125
本文介绍了排序多个JavaScript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Haversine公式的帮助下创建了这个脚本,问题是它不断将我引导到数组的第一个位置,无论我交换了多少次。任何想法?

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 about. Any ideas?

var locations = new Array(
  Array("Brighton", 50.82253, -0.137163),
  Array("Chichester", 50.83761, -0.774936),
  Array("Portsmouth", 50.8166667, -1.0833333),
  Array("Worthing", 50.81787, -0.372882)
);

function deg2rad(degrees){
    radians = degrees * (Math.PI/180);
    return radians;
}

function haversine(lat1,lon1,lat2,lon2) {
    deltaLat = lat2 - lat1;
    deltaLon = lon2 - lon1;
    earthRadius = 3959; // In miles (6371 in kilometers)
    alpha = deltaLat/2;
    beta = deltaLon/2;
    a = Math.sin(deg2rad(alpha)) * Math.sin(deg2rad(alpha)) 
      + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) 
      * Math.sin(deg2rad(beta)) * Math.sin(deg2rad(beta));
    c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    distance = earthRadius * c;
    return distance.toFixed(2);
}

function locationSuccess(position) {

    var places = new Array();
    var userLatitude = position.coords.latitude;
    var userLongitude = position.coords.longitude;

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

    var sorted = places.sort(); // Sort places from low to high 

    /*
    alert(places); // Listed distances unordered
    alert(sorted); // Listed distances in order
    alert(sorted[0]); // Nearest city distance
    */

}

function locationFailed() {
    // Change me to a better error message
    alert("Ooops, we couldn't find you!"); 
}

// Get user's physical location
navigator.geolocation.getCurrentPosition(locationSuccess, locationFailed);


推荐答案

距离数组

您应该将距离放在位置数组中(即作为每个数组的第四个成员元素):

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);
});

这篇关于排序多个JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆