Sort an Array Alphabetically using sort

Tell us what’s happening:

I think i used the right code, but it doesn’t seem to work. I logged the results to the console and nothing happens no matter if i store the result in a variable or change the sort method. Maybe there is an issue with the challenge?

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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36.

The inputs you’re giving are strings and for that the sort method is working just fine without passing it a function.

EDIT: You could also try converting the letters into numbers using the charCodeAt() method on the strings inside the array and then you’ll return the difference between the two values.

Try reading how sort() works

2 Likes

@Flopet17
This means that the example from the exercise is incorrect

function ascendingOrder(arr) {
  return arr.sort(function(a, b) {
    return a - b;
  });
}
ascendingOrder([1, 5, 2, 3, 4]);
// Returns [1, 2, 3, 4, 5]

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

There’s also a note saying - It’s encouraged to provide a callback function to specify how to sort the array items. JavaScript’s default sorting method is by string Unicode point value, which may return unexpected results.

So for regular alphabetical sort, it’s better to go ahead without a callback??

In Firefox:

reverseAlpha([..."sdfgdgf"])
[ "s", "g", "g", "f", "f", "d", "d" ]

In Chrome, which uses a different sorting algorithm:

> reverseAlpha([..."sdfgdgf"])
["s", "d", "f", "g", "d", "g", "f"]

It’s not incorrect per se, but it doesn’t work in some browsers because the callback return value (a < b) does not return what it’s supposed to return (see the documentation :point_up:). If you want to sort things alphabetically, don’t use the callback used in the example.

Also, even where it does kinda work (like in Firefox), or if you just do arr.sort() and rely on the default behaviour, this won’t be sorted alphabetically:

['b', 'C', 'a', 'B', 'c', 'A']

This will work, and if you have something where the alphabetical order is very important, imo it should probably be used:

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

Note it will base the comparison on the system locale (so if I run it, it will use English), but you can pass in locale-specific config. So if you had a string of French words, you could ensure that anything starting with á or é (for example) would be in the correct place in the sorted list. And you can do things like ignore punctuation.

1 Like