Sort an Array Alphabetically using the sort Method not working still

Tell us what’s happening:

Your code so far


function alphabeticalOrder(arr) {
  // Add your code below this line
  return arr.sort(function(a,b) {
    return a > b;
  });
  // Add your code above this line
}
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/70.0.3538.102 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/

I assume you’re using Chrome? The example given (using a < b to sort in reverse alphabetical order) is not correct afaics.

Removing the callback should sort in the correct order by default: it sorts by character code points, and a comes before b, b comes before c, etc.

But for the callback, it should return -1 (or a negative number), 0, or 1 (or a positive number). So b - a, not a > b (which returns true or false instead)

1 Like

I got the same problem using Chrome browser.
With a and b are characters, a-b will return NaN. My solution is a>b ? 1:-1.

2 Likes

If you just want to pass the challenger, just try: return arr.sort();

1 Like

This worked. I got so fed up I looked up the answer to see that is was exactly the same as my solution. Plugged in arr.sort(); worked perfectly. Thank you.

That will work, but it’s unreliable. You pass the challenge, but accidentally.

By default, sort doesn’t sort alphabetically, it sorts by codepoints. So, for example “A a B b C c” will sort “A B C a b c”.

Some of the time that’s ok. Just make sure they’re all uppercase or lowercase characters and you’re fine. Oh and just A-Z/a-z, nö nøn-làtîn älphâbét chårãçtèrß.

But if that is not fine, JS provides a method for comparing strings, designed for use in sorting: localeCompare. To quote:

The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

So as a side-by-side comparison:

[ 'c', 'a', 'B', 'C', 'b', 'A' ].sort()
// [ 'A', 'B', 'C', 'a', 'b', 'c' ]


[ 'c', 'a', 'B', 'C', 'b', 'A' ].sort((a, b) => a.localeCompare(b))
// [ 'a', 'A', 'b', 'B', 'c', 'C' ]
7 Likes