考虑具有以下值的数组数组
var myArray = [
["2001-05","Tom","1000"],
["2001-05","Harry","500"],
["2002-06","Harry","3000"],
["2002-06","Tom","2000"],
....
上面的数组已根据第一个元素排序,即年份, 但是我也希望根据第二个元素对数组进行排序 年组。
输出就像,
var myArray = [
["2001-05","Harry","500"],
["2001-05","Tom","1000"],
["2002-06","Harry","3000"],
["2002-06","Tom","2000"],
....
除了使用嵌套循环进行排序之外,我们可以将数组排序为javascript中的分组排序数组或使用jquery。
答案 0 :(得分:1)
尝试以下方法:
var myArray = [
["2001-05","Tom","1000"],
["2001-05","Harry","500"],
["2002-06","Harry","3000"],
["2002-06","Tom","2000"]
];
var sortedArray = myArray.sort(function (a, b) {
return Number(a[0].replace('-','')) - Number(b[0].replace('-','')) || a[1] > b[1];
});
console.log(sortedArray);
答案 1 :(得分:1)
尝试以下方法:
var myArray = [
["2001","Harry","500"],
["2002","Harry","3000"],
["2002","Tom","2000"],
["2001","Tom","1000"]
];
var sorted = myArray.sort((a,b) =>{
if(a[0] !== b[0])
return a[0] > b[0];
else if(a[1] !== b[1])
return a[1] > b[1];
});
console.log(sorted);

答案 2 :(得分:1)
只需使用数组sort()
即可。它将正确排序数组。
var sortedArray = myArray.sort(function(a, b) {
return a > b ? 1 : -1;
});