In general, sorting by multiple criteria is done like this:
theArray.sort(function(left, right) {
var result = /*...compare first criterion*/;
if (result == 0) {
result = /*...compare second criterion*/;
if (result == 0) {
result = /*...compare third criterion*/;
// ...and so on...
}
}
return result;
});
...where "compare X criterion" results in a negative number if left
should come before right
, 0 if they're the same for that criterion, and a positive number if right
should come before left
.
That works because we only need to evaluate our second criterion if the entries are "the same" according to the first, only need to look at the third if the first and second are "the same," etc.
That's for a hardcoded series. It can easily be adapted for a series defined by an array of comparisons to make (using a loop that breaks when result
is not 0).
Simple example of the hardcoded version:
var array = [
{a: 4, b: 3, c: 5},
{a: 1, b: 2, c: 7},
{a: 4, b: 4, c: 4},
{a: 4, b: 4, c: 2},
{a: 4, b: 4, c: 6},
{a: 2, b: 8, c: 9},
{a: 2, b: 9, c: 8}
];
show("Unsorted", array);
array.sort(function(left, right) {
var result = left.a - right.a;
if (result == 0) {
result = left.b - right.b;
if (result == 0) {
result = left.c - right.c;
}
}
return result;
});
show("Sorted", array);
function show(label, a) {
console.log(
label,
a.map(function(entry) {
return "a:" + entry.a +
",b:" + entry.b +
",c:" + entry.c;
})
);
}
.as-console-wrapper {
max-height: 100% !important;
}