Sort an Array Alphabetically using sort

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