简体   繁体   English

数值排序二维数组

[英]Numerical sorting 2d array

I am REALLY new at JS, and I am trying to sort this 2d array by the second value. 我真的是JS的新手,我正在尝试按第二个值对2d数组进行排序。 I swapped the 1st and 2nd values around so I can use .sort(), but since it is supposed to be a number I used function(a, b){return a - b}. 我交换了第一个和第二个值,因此可以使用.sort(),但是由于应该是一个数字,因此我使用了function(a,b){return a-b}。 It still doesn't work. 它仍然不起作用。

function orderListItemQuantity(){
for (i=0;i<items.length; i++){
    var temp = items[i][0];
    items[i][0] = items[i][1];
    items[i][1] = temp;
}
items.sort(function(a, b){return a - b});
for (i=0;i<items.length; i++){
    var temp = items[i][0];
    items[i][0] = items[i][1];
    items[i][1] = temp;
}
refreshList();

} }

Use the brackets notation to sort by the 2nd item (index 1) of each sub-array. 使用括号符号按每个子数组的第二项(索引1)排序。

Example: 例:

 var items = [[1, 3], [1, 1], [1, 2]]; items.sort(function(a, b) { return a[1] - b[1]; }); console.log(JSON.stringify(items)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM