I'm following Free Code Camp's "JavaScript Algorithms and Data Structures" tutorial.
I have a challenge and a hint and solution to this challenge, but I don't understand the solution, neither the hint.
Here is the challenge:
Use the sort method in the alphabetical Order function to sort the elements of arr in alphabetical order.
Here is the hint:
Hint #1
You need to use a “compare function” as the callback function of the sort method.
For example, the following is how you would sort an array in reverse alphabetical order.
function reverseAlphabeticalOrder(arr) {
return arr.sort(function(a, b) {
return a === b ? 0 : a < b ? 1 : -1;
});
}
reverseAlphabeticalOrder(["l", "h", "z", "b", "s"]);
Here is the solution:
Solution #1
function alphabeticalOrder(arr) {
return arr.sort(function(a, b) {
return a === b ? 0 : a < b ? -1 : 1;
});
}
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
Here is the link to this challenge
Could you please explain the solution. Once I'll get the solution explained, I will be able to understand the hint too.
Thank you very much in advance for your help.
Best regards, Helena