Sort an Array Alphabetically using the sort Method not working

Tell us what’s happening:
I do not understand why is this not sorting my array. My logic was to reverse the given algorithm. I even checked the hints and the code was identical. I even tries copy the solution code from hints but nothing works.

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/74.0.3729.169 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 recommend reading about how sort() works.


But try this.

  // Add your code below this line
  return arr.sort(function(a,b) {
   if(a< b) { return -1; }
    if(a > b) { return 1; }
    return 0;
  });
  // Add your code above this line
}

Another solution would be to just use arr.sort(), since it’s sorting it alphabetically too. However, the first solution can be also used for array of objects.

Thanks. I think I understand now. But it seems that the original task and solution has mistakes. Very confusing.

It’s working for me. Are you getting any errors? If not you how do you know it’s not working? Try adding a console.log to the function call so you can see the result.

function alphabeticalOrder(arr) {
  // Add your code below this line
  return arr.sort(function(a, b) {
    return a > b;
  });
  // Add your code above this line
}
console.log(alphabeticalOrder(["a", "d", "c", "a", "z", "g"]));

His code doesn’t work for me, but the one I posted does.

Yes, I tried logging the result but every time I just got the same array as input.

It depends on browser, the challenge description should be changed

1 Like