按两个数字项对2D数组排序

时间:2019-05-26 09:15:06

标签: javascript arrays sorting columnsorting

我想先按第5列然后按第4列对2D数组进行排序。它们代表橄榄球联赛表格上的PTS和GD。

var table = [
  ["teamA", 6, 2, 0, 2, 7],
  ["teamB", 6, 1, 1, 6, 7],
  ["teamC", 6, 2, 1, 8, 7]
];

我已经适应了在论坛上收到的好建议: Sorting 2D Array by numeric item

我复制了函数,以便首先按PTS排序,然后按GD排序。

console.log(table.sort(comparePTS));

console.log(table.sort(compareGD));

function comparePTS(a, b) {
  return b[5] - a[5]

}
function compareGD(a, b) {
  return b[4] - a[4]
}

尽管可以,但它两次显示表格:

由PTS排序

[ [ "teamA", 6, 2, 0, 2, 7 ], [ "teamB", 6, 1, 1, 6, 7 ], [ "teamC", 6, 2, 1, 8, 7 ] ]

由PTS和GD排序

[ [ "teamC", 6, 2, 1, 8, 7 ], [ "teamB", 6, 1, 1, 6, 7 ], [ "teamA", 6, 2, 0, 2, 7 ] ]

这似乎是最笨拙的解决方案。在单个功能中实现此目标的最佳方法是什么?预先感谢。

1 个答案:

答案 0 :(得分:0)

您可以链接订购功能,直到有区别将此值返回到排序功能为止。

const
    PTS = a => a[5],
    GD = a => a[4],
    ASC = fn => (a, b) => fn(a) - fn(b),
    DESC = fn => (a, b) => fn(b) - fn(a),
    sortBy = fns => (a, b) => {
        var value;
        fns.some(fn => value = fn(a, b));
        return value;
    };

var table = [["teamA", 6, 2, 0, 2, 7], ["teamB", 6, 1, 1, 6, 7], ["teamC", 6, 2, 1, 8, 7]];
   
table.sort(sortBy([DESC(PTS), DESC(GD)]));

console.log(table);
.as-console-wrapper { max-height: 100% !important; top: 0; }