javascript 排序二维Javascript数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6490343/
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
sorting 2 dimensional Javascript array
提问by gmhk
Can any one help me in sorting a 2 Dimensional Array
任何人都可以帮助我对二维数组进行排序吗
Which will have the data in the following format
其中将包含以下格式的数据
[2, All are fine]
[4, All is Well]
[1, Welcome Code]
[9, Javascript]
After sorting it should look like
[2, All are fine]
[4, All is Well]
[9, Javascript]
[1, Welcome Code]
Main thing that i am focussing is to sort based on Text not on the ID
我关注的主要内容是基于文本而不是 ID 进行排序
回答by Gijs
ary.sort(function(a, b) { return (a[1] < b[1] ? -1 : (a[1] > b[1] ? 1 : 0)); });
See: http://jsfiddle.net/tdBWh/for this example, and MDC for documentation.
有关此示例,请参阅:http: //jsfiddle.net/tdBWh/,有关文档的 MDC。
回答by JMax
You can use this kind of code :
您可以使用这种代码:
function sortMultiDimensional(a,b)
{
// for instance, this will sort the array using the second element
return ((a[1] < b[1]) ? -1 : ((a[1] > b[1]) ? 1 : 0));
}
and then use the sort method :
然后使用排序方法:
myArray.sort(sortMultiDimensional);
Regards,
问候,
Max
最大限度
回答by user187291
ary.sort(function(x,y) { return x[1].localeCompare(y[1]) })