javascript 按第二个值对二维数组进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3524827/
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-10-25 01:24:30  来源:igfitidea点击:

Sort a 2D array by the second value

javascript

提问by Noe

I have an array and I want to sort by the number field not the name.

我有一个数组,我想按数字字段而不是名称排序。

var showIt = [
  ["nuCycleDate",19561100],
  ["ndCycleDate",19460700],
  ["neCycleDate",0],
  ["nlCycleDate",0]
];

Thanks

谢谢

回答by lincolnk

you can provide sortwith a comparison function.

您可以提供sort比较功能。

showIt.sort(function(a,b){
    return a[1] - b[1];
});

aand bare items from your array. sort expects a return value that is greater than zero, zero, or less than zero. the first indicates acomes before b, zero means they are equal, the last option means bfirst.

a并且b是您阵列中的项目。sort 期望返回值大于零、零或小于零。第一个表示a在之前b,零表示它们相等,最后一个选项表示b在前。

回答by Vanessa Phipps

This siteadvises against using the arguments without assigning to temporary variables. Try this instead:

该站点建议不要在不分配临时变量的情况下使用参数。试试这个:

showIt.sort(function(a, b) {
    var x = a[1];
    var y = b[1];
    return x - y;
});