I stumbled upon some unexpected behaviour when solving the following problem:
“Make a comparison function such that you can sort an array in reverse alphabetical order.”
I did solve the problem, but my initial solution did not work and I do not understand why. I also want to mention that I know one can simply use .sort() and .reverse() to achieve the same goal, but that is not the intent here.
My initial approach was the following:
function reverseAlphabetical(a, b) {
let list = [a, b];
list.sort();
if (list[0] == a) {
return true;
} else {
return false;
}
}
let fruits = ["melon", "apple", "orange", "pear"];
fruits.sort(reverseAlphabetical);
console.log(fruits);
This simply outputs the same array fruits. Same happens when I replace true by 1 and false by 0. If I replace false by -1 however, it works.
I was under the impression that the return value 0 means that a and b are equal, and hence should not be exchanged, while -1 means that a should be sorted before b, again meaning they should not be exchanged. I can not see why the return values 0 and -1 should yield different results. Does anybody have an explanation?