Bug in: Sort an Array Alphabetically using the sort Method

Tell us what’s happening:

Tested my script locally through VSCode/Node.js and it is getting desired outputs. Even tried copy/paste solution from FCC and it seems the checks are experiencing a bug.

Your code so far
return arr.sort((a, b) => a > b);


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/71.0.3578.98 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

Compare function, the argument of sort() method expects one of three outcomes:

  1. Result is less than 0
  2. Result equals 0
  3. Result is more than 0

return a > b; doesn’t give numeric outcome unfortunately, to compare and have numeric outcome you could use something like a.localeCompare(b), the method that compares strings and returns numeric value as it’s expected by .sort() method.

I don’t know if this is unique to the most recent version of Chrome, but it looks like that’s the culprit.

The .sort() callback function is intended to return a number. If that number is negative, then a should have a lower index. If the number is 0, then nothing is changed. If the number is positive, then a should have a higher index.

a > b doesn’t return a number. It returns a boolean. When a boolean is treated as a number, true is treated as 1 and false is treated as 0. So, you can see where this would cause sorting to fail.

So why does it seem to work in some environments (like a Node repl or Firefox)? Well, it looks like in some cases a more generous implementation of .sort() is being applied, which understands a boolean return value. I said that I don’t know if this is a recent change in Chrome or not. It could be that they have become more strict. I never tried sorting this way, so I don’t know if it was previously supported.

So why does FCC say this?

function reverseAlpha(arr) {
 return arr.sort(function(a, b) {
   return a < b;
 });
}

Because a mistake was made. This is why I suspect that Chrome has become more strict in a recent version.
This should definitely be reported as a bug. Bugs can be reported as GitHub Issues. Whenever reporting a bug, please check first that there isn’t already an issue for it and provide as much detail as possible.

This has been reported and fixed on master (site not update).

2 Likes

Excellent! Thanks for tracking that down.