I want to sort a 2D array first by column 5, then by column 4. They represent the PTS and GD on a football league table.
var table = [
["teamA", 6, 2, 0, 2, 7],
["teamB", 6, 1, 1, 6, 7],
["teamC", 6, 2, 1, 8, 7]
];
I've adapted the great advice I received on the forum: Sorting 2D Array by numeric item
I replicated the function so that it first sorts by PTS and then by 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]
}
Although this works, it displays the table twice:
Sorted by PTS
[ [ "teamA", 6, 2, 0, 2, 7 ], [ "teamB", 6, 1, 1, 6, 7 ], [ "teamC", 6, 2, 1, 8, 7 ] ]
Sorted by PTS and GD
[ [ "teamC", 6, 2, 1, 8, 7 ], [ "teamB", 6, 1, 1, 6, 7 ], [ "teamA", 6, 2, 0, 2, 7 ] ]
And this seems the most clunky solution. What's the best way to achieve this within a single function? Thanks in advance.