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

EBM*_*EBM 1 javascript sorting

可能重复:
如何对javascript对象数组进行排序?

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

function Location(name, latitude, longitude){
this.latitude = latitude;
this.longitude = longitude;
this.name = name;
}
Run Code Online (Sandbox Code Playgroud)

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

Poi*_*nty 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);
  });
}
Run Code Online (Sandbox Code Playgroud)

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

你可以通过将数组和参考点坐标传递给该函数来调用它.如果您想要传递"位置"实例,则应该清楚要更改的内容.