如何在自定义顺序中对JavaScript中的数组进行排序?

时间:2012-06-05 23:25:01

标签: javascript sorting

  

可能重复:
  How to sort an array of javascript objects?

嗯,更精确,我有以下课程:

function Location(name, latitude, longitude){
this.latitude = latitude;
this.longitude = longitude;
this.name = name;
}

我希望按照与给定位置(类似于此类的对象)的接近顺序对这些对象的数组进行排序。

5 个答案:

答案 0 :(得分:7)

你需要一个比较器功能:

function sortLocations(locations, lat, lng) {
  function dist(l) {
    return (l.latitude - lat) * (l.latitude - lat) +
      (l.longitude - lng) * (l.longitude - lng);
  }

  locations.sort(function(l1, l2) {
    return dist(l1) - dist(l2);
  });
}

我不打扰那里的方根,因为我认为没必要。此外,我不会考虑球面几何形状的任何奇怪,因为我不认为它的复杂性是值得的。但是,如果您有自己的现有计算距离的方法,可以插入而不是我在上面输入的内容。

只需将数组和参考点坐标传递给该函数即可调用它。如果您想要传递“位置”实例,则应该清楚要更改的内容。

答案 1 :(得分:3)

请参阅:Sorting an array of JavaScript objects

另一个答案的简单lat1-lat2 + lon1-lon2公式对于数学2-d平面来说是不正确的,对于椭圆体地球更是如此。除非距离确实不需要准确,否则您应该使用半正式公式作为排序功能。

来自:http://www.movable-type.co.uk/scripts/latlong.html

var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();

var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c;

答案 2 :(得分:1)

您想将功能传递给Array.prototype.sortThis link对此有一个很好的解释。我知道这不适合球形几何,但你会想要这样的东西:

var home = new Location("Home", 40, -50);
arr.sort(function(a, b){
    var dist1 = Math.sqrt(Math.pow(home.latitude-a.latitude, 2) + Math.pow(home.longitude-a.longitude, 2)),
        dist2 = Math.sqrt(Math.pow(home.latitude-b.latitude, 2) + Math.pow(home.longitude-b.longitude, 2));
    if (dist1 < dist2) { 
        return -1;
    }
    else {
        return 1;
    }
});

答案 3 :(得分:1)

function Location(name, latitude, longitude){
this.latitude = latitude;
this.longitude = longitude;
this.name = name;
};

this.locations.push(new Location());

 this.locations.sort(function (a, b) { return a.latitude - b.latitude ; });

您需要将您的位置存储在数组中。

答案 4 :(得分:1)

Location.distance = function ( loc1, loc2 ) {
    return Math.sqrt(
        Math.pow( loc2.longitude - loc1.longitude, 2 ) +
        Math.pow( loc2.latitude - loc1.latitude, 2 )
    );
};

Location.prototype.sortByProximity = function ( arr ) {
    var that = this;
    arr.sort(function ( a, b ) {
        return Location.distance( that, a ) - Location.distance( that, b );
    });
};

首先,你有一个静态函数Location.distance,它接受​​两个Location个实例并返回一个表示它们相对距离的值。

其次,您有一个sortByProximity方法,该方法作为Location个实例上的方法调用,并且需要一个Location个实例数组作为其第一个参数。

用法:

baseLocation.sortByProximity( locArr );
// locArr is now sorted in regard to baseLocation

现场演示: http://jsfiddle.net/hGp66/