Sort an Array Alphabetically using the sort Method - BUG?

Tell us what’s happening:
Hello. It took me a while to get this code right but I finally got it. So that’s not the issue here. The issue is that I don’t understand why it took me so long while folowing instructions and even checking hint solution.

I wonder if the instructions and hint (solution) of this exercise are mistaken? To use the sort method to sort an array by alphabet, the callback inside the sortfunction must return 1 or -1. No? Yes?
The solution in hint does not do that. Same thing for the example in the exercise instructions.

Can someone confirm this? Is there a mistake in exercise or am I misunderstanding something?

Thank you.

Your code so far


function alphabeticalOrder(arr) {
  // Add your code below this line
  return arr.sort((a,b) => a > b ? 1 : -1)
  // 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 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 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/

The example is out of date as of September last year for Chrome. Go off official documentation not the hint (sort((a, b) => a > b) is not going to work for alphabetical sorting). Afaik there is an update to FCC which fixes the example but isn’t live at the minute.

Note that it isn’t wrong per se, it just doesn’t work in one browser after the engine that browser uses changed the way it’s sort algorithm worked. The actual JS spec doesn’t have much of an opinion either way (you can argue the current example should work fine according to the spec, devs for V8 decided it should not work for sensible reasons).

1 Like

Huh. Okay, that’s interesting. Thanks! :slight_smile:

1 Like