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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:30:31  来源:igfitidea点击:

Javascript: sort multidimensional array

javascriptsortingmultidimensional-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.sortmethod has an optional parameter, which is a function reference for a custom compare. the return values are >0meaning bfirst, 0meaning aand bare equal, and <0meaning afirst.

javascript 的array.sort方法有一个可选参数,它是自定义比较的函数引用。返回值是>0含义b优先,0含义ab相等,<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 locationas a variable as it is already system defined.

到目前为止发布的两个排序函数都应该可以工作,但是您的主要问题是将其location用作变量,因为它已经是系统定义的。