Sort an Array Alphabetically using the sort Method- should there be a correction in this lesson

Tell us what’s happening:

I think there should be a correction in this lesson. the code for Alphabetically reversing the array is wrong

function reverseAlpha(arr) {
  return arr.sort(function(a, b) {
    return a < b;
  });
}
reverseAlpha(['l', 'h', 'z', 'b', 's']);
// Returns ['z', 's', 'l', 'h', 'b']

instead, i think this should be the right code:

function reverseAlpha(arr) {
    return arr.sort(function(a, b) {
    if (a > b){return -1}
    else if(a<b){return 1};
    });
  }
  reverseAlpha(['l', 'h', 'z', 'b', 's']);
  // Returns ['z', 's', 'l', 'h', 'b']








User Agent is: <code>Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36</code>.

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

Technically it would be:

  if (a > b) {
    return 1;
  } else if (a < b) {
    return -1;
  } else {
    return 0;
  }

But I think it works because yours will just returns undefined which works effectively the same as 0 in the implementation or sort.

But we don’t really fix those things on this forum. If you want, you can go to the github repo, see if this issue has been raised and raise it if not. You can even fix it if you want.

1 Like

I believe that a fix for this has already been made and is waiting for QA and the next site update.

1 Like

Thank you Kevin. so, returning 0 is the case when a and b are equal right?

1 Like

Yes, that is correct - that is how sort is supposed to work. But like I said, yours is just returning undefined in that case, which I guess is getting interpreted the same way. Mine is just a little more explicit.

1 Like

It could also be:

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