Sort(): Functional Programming

I don’t get why this wouldn’t work…

My code so far:


function alphabeticalOrder(arr) {
    // Add your code below this line
    return arr.sort((a, b) => a > b);

    
    // Add your code above this line
  };



  console.log(alphabeticalOrder(["a", "d", "c", "a", "z", "g"]));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method

This actually worked:

function alphabeticalOrder(arr) {
  // Add your code below this line
  return arr.sort();
  // Add your code above this line
}
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);

I’m a bit confused here. The challenge says:

Note: It’s encouraged to provide a callback function to specify how to sort the array items. JavaScript’s default sorting method is by string Unicode point value, which may return unexpected results.

Appreciate any bit of explanation.

I faced this same issue, you think that the callback of sort would return true and false for the sorting, but it uses 1,0, and -1.

      return arr.sort((a, b) => a > b ? 1 : -1);

//or even better

      return arr.sort((a, b) => a > b ? 1:a<b?-1:0);

return 1 if you want a to be before b, -1 for b before a and 0 to not swap them. The first way is sufficient for the quiz, but I think it’s nice that we are given the option to return 0 and not alter the order of those 2 elements. that wouldn’t be possible if the sort callback used a boolean.

1 Like

I saw this in MDN too. The challenge examples were confusing.

Thank you! :smiley: