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

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

#1

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

Sort an Array Alphabetically using the sort Method (solution in hint doesn't work)
#2

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.


#3

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


#4

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


#5

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.


#6

It could also be:

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