Sort an Array Alphabetically using the sort Method (not working?)

Hi, i’m not sure if this challenge has been changed or not, but this alphabetical arrangement code seems to work perfectly in repl.it, but comes up failing in fcc.

Your code so far


function alphabeticalOrder(arr) {
  // Add your code below this line
  return arr.sort((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 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 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/

It doesn’t seem to be working on repl.

oops, yeah thats the wrong code, hold up. try this:

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

It’s the same code except older syntax.

If you are sorting characters, you don’t need to pass down a callback as the default is sorting by unicode.

So you can simply do

return arr.sort();

2 Likes

ohhh, okay. So sort natively sorts unicode characters. there no need to specify what. Thank you!

You can sort like this if it has all small case character
const sortedArray = [“a”, “d”, “c”, “a”, “z”, “g”].sort((a,b) => a.charCodeAt() - b.charCodeAt())

If compareFunction is supplied, all non- undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to compareFunction ). If a and b are two elements being compared, then:

  • If compareFunction(a, b) is less than 0, sort a to an index lower than b (i.e. a comes first).
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to an index lower than a (i.e. b comes first).
  • compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.

~MDN page for Array.prototype.sort()

Your sort function returns a boolean.