Here is the context:
function compare (value1, value2) {
if(value1 < value2) {
return -1;
} else if (value1 > value2) {
return 1;
The sort
method takes an optional comparison function that determines the resulting sort order based on the following:
value1
to a lower index than value2
value1
and value2
unchanged with respect to each othervalue1
to a higher index than value2
Note that given these rules, it's possible to shorten your comparison function to the following:
function compare(value1, value2) {
return value1 - value2;
}