Javascript:对多维数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3886165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: sort multidimensional array
提问by Jeff
After creating a multi-dim array like this, how do I sort it?
创建这样的多维数组后,如何对其进行排序?
Assuming 'markers' is already defined:
假设已经定义了“标记”:
var location = [];
for (var i = 0; i < markers.length; i++) {
location[i] = {};
location[i]["distance"] = "5";
location[i]["name"] = "foo";
location[i]["detail"] = "something";
}
For the above example, I need to sort it by 'distance'. I've seen other questions on sorting arrays and multi-dim arrays, but none seem to work for this.
对于上面的示例,我需要按“距离”对其进行排序。我已经看到有关排序数组和多维度数组的其他问题,但似乎没有一个适用于此。
回答by lincolnk
location.sort(function(a,b) {
// assuming distance is always a valid integer
return parseInt(a.distance,10) - parseInt(b.distance,10);
});
javascript's array.sort
method has an optional parameter, which is a function reference for a custom compare. the return values are >0
meaning b
first, 0
meaning a
and b
are equal, and <0
meaning a
first.
javascript 的array.sort
方法有一个可选参数,它是自定义比较的函数引用。返回值是>0
含义b
优先,0
含义a
和b
相等,<0
含义a
优先。
回答by user113716
Have you tried this?
你试过这个吗?
location.sort(function(a,b) {
return a.distance - b.distance;
});
回答by Gus
Both sort functions posted so far should work, but your main problem is going to be using location
as a variable as it is already system defined.
到目前为止发布的两个排序函数都应该可以工作,但是您的主要问题是将其location
用作变量,因为它已经是系统定义的。