使用javascript

时间:2018-04-06 11:17:20

标签: javascript arrays sorting

我有这个数组:

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

我希望:

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

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

我尝试了sort(),我还尝试使用sort(compare)

function compare(x, y) {
  return x - y;
}

4 个答案:

答案 0 :(得分:5)

您可以.sort()使用Array Destructuring,如下所示:

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

<强>演示:

&#13;
&#13;
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);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

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

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

<强>演示:

&#13;
&#13;
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);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0 }
&#13;
&#13;
&#13;

答案 1 :(得分:4)

您需要比较嵌套数组中的第一个元素,因为您希望根据该数字进行排序。

function compare(x, y) {
  return y[0] - x[0];
}

&#13;
&#13;
var data = [
  [1, 'a'],
  [2, 'b'],
  [1, 'd'],
  [9, 'e'],
  [1, 'f'],
  [11, 'g'],
  [9, 'h'],
  [3, 'i']
];

function compare(x, y) {
  return y[0] - x[0];
}

data.sort(compare);

console.log(data);
&#13;
&#13;
&#13;

如果您想基于第二个元素进行排序(如果第一个元素相同则进行二级排序),然后使用String#localeCompare方法进行比较。

function compare(x, y) {
  return y[0] - x[0] || x[1].localeCompare(y[0]);
}

&#13;
&#13;
var data = [
  [2, 'b'],
  [1, 'd'],
  [9, 'e'],
  [1, 'f'],
  [1, 'a'],
  [11, 'g'],
  [9, 'h'],
  [3, 'i']
];

function compare(x, y) {
  return (y[0] - x[0]) || x[1].localeCompare(y[1]);
}

data.sort(compare);

console.log(data);
&#13;
&#13;
&#13;

答案 2 :(得分:1)

根据第一个元素(即数字)比较元素。

&#13;
&#13;
var a = [ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ];

a = a.sort((a,b) => {
    return b[0] - a[0]
});

console.log(a)
&#13;
&#13;
&#13;

答案 3 :(得分:1)

使用sort 比较第一个元素,如果第一个元素相同,则比较第二个元素

arr.sort( (a,b) => (b[0] - a[0]) || (b[1] - a[1]) )

<强>演示

&#13;
&#13;
var arr = [ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ];

arr.sort( (a,b) => (b[0] - a[0]) || (b[1] - a[1]) );

console.log(arr);
&#13;
&#13;
&#13;

相关问题