Array.prototype.sort
function expects a function as a parameter, which accepts two parameters and returns any of -1, 0 or 1
.
I am a very big fan of functional programming, so I came up with this. This offers flexibility.
- You can sort based on any element
- You can even reverse the order of sorting
- You can customize, how the objects have to be compared.
function basicComparator(first, second) {
if (first === second) {
return 0;
} else if (first < second) {
return -1;
} else {
return 1;
}
}
function compareNthElements(n, comparatorFunction, reverse) {
return function(first, second) {
if (reverse === true) {
return comparatorFunction(second[n], first[n]);
} else {
return comparatorFunction(first[n], second[n]);
}
}
}
Thats it. Now, call the sort
function like this
arry.sort(compareNthElements(1, basicComparator, true)); // Sorts first field and in reverse
arry.sort(compareNthElements(2, basicComparator)); // Sorts second field
arry.sort(function (a, b) { return a[2] - b[2]; });
– Givi Jan 2 '14 at 12:12