Click here to Skip to main content
15,668,126 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I would need to sort an array of letters considering the case of each string, to be more specific, I want upper case letters to go first, how can I do this? I found a solution that handles this but there is one bug that I don`t know how to fix:
var arr = ["T", "h", "e", "c", "a", "t", "s", "a", "t", "o", "n", "t", "h", "e", "m", "a", "t"];
arr.sort(function(a, b)
    var x = a.toLowerCase(), y = b.toLowerCase();
    if(x < y) {return -1}
    else if (x > y ) {return 1} 
    else {return 0};
}); //-> ["a", "a", "a", "c", "e", "e", "h", "h", "m", "n", "o", "s", "t", "T", "t", "t", "t"]

Why won`t the capital t be first on the list of 'T'`s, like this :
["a", "a", "a", "c", "e", "e", "h", "h", "m", "n", "o", "s",  "T", "t", "t", "t", "t"]

P.S I am sorry for previous confusing question. I am trying to sort an array according to the case.

What I have tried:

.sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());

The output is the same
Updated 15-Aug-16 9:54am
Karthik_Mahalingam 15-Aug-16 9:26am    
there is a bug in Google chrome's Sort, whereas it works fine with IE and Firefox

Why capital T doesn't go first?
It don't go first because you asked it this way.
It is hard to think this code is yours! 3 lines and you don't understand the code.

This is homework, so you have to find yourself what is wrong.
Advice: read the code, the problem should be obvious. If you don't understand something, search for definition and usage.
Share this answer
AlexLearne 15-Aug-16 15:25pm    
I am sorry for confusing you, I updated the question. I understand what the code does. Well, I think I do
Patrice T 15-Aug-16 15:56pm    
The 'T' problem is not on the changes you made.
There is not much more places to look.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900