使用javascript对数组进行数字排序

Cha*_*tte 1 javascript arrays sorting

我有这个数组:

[ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ]
Run Code Online (Sandbox Code Playgroud)

我希望:

[ [ 11, 'g' ], [ 9, 'e' ], [ 9, 'h' ], [ 3, 'i' ], [ 2, 'b' ], [ 1, 'a' ], [ 1, 'd' ], [ 1, 'f' ] ]
Run Code Online (Sandbox Code Playgroud)

我怎么能用javascript做到这一点?

我试过了sort(),我也尝试过sort(compare):

function compare(x, y) {
  return x - y;
}
Run Code Online (Sandbox Code Playgroud)

Moh*_*man 5

您可以使用.sort()具有Array Destructuring这样的:

function compare([a], [b]) {
  return b - a;
}
Run Code Online (Sandbox Code Playgroud)

演示:

let a = [ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ];

a.sort(compare);

function compare([a], [b]) {
  return b - a;
}

console.log(a);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)


如果第一个元素匹配,您也可以基于第二个元素进行排序:

function compare([a, c], [b, d]) {
  return (b - a) || c.localeCompare(d)
}
Run Code Online (Sandbox Code Playgroud)

演示:

let a = [ [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ], [ 1, 'a' ] ];

a.sort(compare);

function compare([a, c], [b, d]) {
  return (b - a) || c.localeCompare(d);
}

console.log(a);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0 }
Run Code Online (Sandbox Code Playgroud)