Javascript - sorting array by multiple criteria
Here is a cleaner and shorter version that does not require a bunch of nested if/else cases:
const sorted = arr.sort((a,b) => {
const [a1, a2] = a.title.split(' - ').map(Number);
const [b1, b2] = b.title.split(' - ').map(Number);
return a1 - b1 || a2 - b2;
});
In pseudocode, the logic would be the following:
Procedure: comparator(a,b)
- If
a < b
thenreturn -1
- If
a = b
then callcomparator(a1, b1)
recursively, wherea1
andb1
are the comparable values of the next level in the sorting. - If
a > b
thenreturn 1
In your concrete case, you can do simply do it by modifying your code a bit:
if (keyA < keyB) {
return -1;
} else if (keyA > keyB) {
return 1;
} else { // keyA == keyB
if (titleA < titleB) {
return -1;
} else if (title > titleB) {
return 1;
} else {
return 0;
}
}
Try this:
arr.sort(function(a, b){
var titleA = a.title;
var titleB = b.title;
var arrA = titleA.split(' - ');
var arrB = titleB.split(' - ');
var keyA1 = parseInt(arrA[0]), keyA2 = parseInt(arrA[1])
keyB1 = parseInt(arrB[0]), keyB2 = parseInt(arrB[1]);
// Compare the 2 keys
if (keyA1 < keyB1) return -1;
if (keyA1 > keyB1) return 1;
if (keyA2 < keyB2) return -1;
if (keyA2 > keyB2) return 1;
return 0;
});