While I am aware that the OP wanted to sort an array of numbers, this question has been marked as the answer for similar questions regarding strings. To that fact, the above answers do not consider sorting an array of text where casing is important. Most answers take the string values and convert them to uppercase/lowercase and then sort one way or another. The requirements that I adhere to are simple:
- Sort alphabetically A-Z
- Uppercase values of the same word should come before lowercase values
- Same letter (A/a, B/b) values should be grouped together
What I expect is [ A, a, B, b, C, c ] but the answers above return A, B, C, a, b, c. I actually scratched my head on this for longer than I wanted (which is why I am posting this in hopes that it will help at least one other person). While two users mention the localeCompare function in the comments for the marked answer, I didn't see that until after I stumbled upon the function while searching around. After reading the String.prototype.localeCompare() documentation I was able to come up with this:
var values = [ "Delta", "charlie", "delta", "Charlie", "Bravo", "alpha", "Alpha", "bravo" ];
var sorted = values.sort((a, b) => a.localeCompare(b, undefined, { caseFirst: "upper" }));
// Result: [ "Alpha", "alpha", "Bravo", "bravo", "Charlie", "charlie", "Delta", "delta" ]
This tells the function to sort uppercase values before lowercase values. The second parameter in the localeCompare function is to define the locale but if you leave it as undefined it automatically figures out the locale for you.
This works the same for sorting an array of objects as well:
var values = [
{ id: 6, title: "Delta" },
{ id: 2, title: "charlie" },
{ id: 3, title: "delta" },
{ id: 1, title: "Charlie" },
{ id: 8, title: "Bravo" },
{ id: 5, title: "alpha" },
{ id: 4, title: "Alpha" },
{ id: 7, title: "bravo" }
];
var sorted = values
.sort((a, b) => a.title.localeCompare(b.title, undefined, { caseFirst: "upper" }));