我想对嵌套数组(数组中的数组)进行排序,即我的数组看起来像这样
calMonthlyPay(200, 6)
为此,我编写了此逻辑
const input = [[3,9],[7,12],[3,8],[6,8],[9,10],[2,9],[0,9],[3,9],[0,6],[2,8]]
但是这将第一个元素设为const input = [[3,9],[7,12],[3,8],[6,8],[9,10],[2,9],[0,9],[3,9],[0,6],[2,8]]
function sort (a,b) {
if (a[0] < b[0]) return -1
if (a[0] > b[0]) return 1
if (a[0] === b[0]) {
if (a.length > 1 && b.length > 1) {
return sort(a.slice(0, 1), b.slice(0,1))
}
else return 0
}
}
console.log(input.sort((a,b) => {
return sort(a,b)
}))
而不是[0,9]
,而给定了[0, 6]
而不是[2, 9]
。
我想要的是
所以[2,8]
应该在[0, 6]
之前...
答案 0 :(得分:4)
您只需进行a[0] - b[0] || a[1] - b[1]
的回调:
const input = [[3,9],[7,12],[3,8],[6,8],[9,10],[2,9],[0,9],[3,9],[0,6],[2,8]]
console.log(input.sort((a,b) => a[0] - b[0] || a[1] - b[1]))
如果数组的长度是任意的,那么您确实需要一个单独的命名函数:
const sort = (a, b) => a[0] - b[0] || sort(a.slice(1), b.slice(1));
const input = [[3,9],[7,12],[3,8],[6,8],[9,10],[2,9],[0,9],[3,9],[0,6],[2,8]]
console.log(input.sort((a,b) => a[0] - b[0] || a[1] - b[1]))