如何在自定义顺序中对JavaScript中的数组进行排序? [英] How to sort an array in JavaScript in a customized order?
问题描述
可能重复:
如何对javascript对象数组进行排序?
嗯,更精确,我有以下课程:
Well, more preciselly, I have the following class:
function Location(name, latitude, longitude){
this.latitude = latitude;
this.longitude = longitude;
this.name = name;
}
我想按照靠近的顺序对这些对象的数组进行排序给定的位置(像这样的类的对象)。
And I want to sort an array of these objects, by order of proximity to a given Location (an object of a class like this one).
推荐答案
你需要一个比较器函数:
You'll need a comparator function:
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);
});
}
我不打扰那里的平方根因为我不认为这是必要的。此外,我不会考虑球面几何形状的任何奇怪,因为我不认为它的复杂性是值得的。但是,如果您有自己现有的计算距离的方法,可以插入而不是我上面输入的内容。
I don't bother with the square roots there because I don't think it's necessary. Also I'm not accounting for any weirdness from spherical geometry, because again I don't think it's worth the complexity. However, if you have your own existing way to compute a distance, it could be plugged in instead of what I typed above.
你只需要通过你的方式来调用它数组,加上参考点坐标,到该函数。如果您想要传递位置实例,则应该清楚要更改的内容。
You'd call that by just passing your array, plus the reference point coordinates, to that function. If you wanted to pass a "Location" instance instead it should be clear what to change.
这篇关于如何在自定义顺序中对JavaScript中的数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!