PDA

View Full Version : Sorting alphabetically but not case sensitive


NZ_Tango
11-26-2002, 03:22 AM
Hi,

I'm just using the default sort() method on an array full of peoples names, however those who have the first letter of their name in lowercase, get pushed to the end, because it treats E as coming before e as an example.

How can I get around this? Appreciate any help, Cheers.

x_goose_x
11-26-2002, 03:32 AM
make everything the same case

object.toLowerCase();

or

object.toUpperCase();

NZ_Tango
11-26-2002, 04:36 AM
That would work but the names would lose their formatting for presentation purposes on the site.

glenngv
11-26-2002, 05:45 AM
try this:


var arr = new Array("javascript","Java","c++","BASIC","html");
arr.sort(caseInsensitiveSort);
var str="";
for (var i=0;i<arr.length;i++) str+=arr[i]+"\n";
alert(str)

function caseInsensitiveSort(a, b)
{
var ret = 0;
a = a.toLowerCase();b = b.toLowerCase();
if(a > b)
ret = 1;
if(a < b)
ret = -1;
return ret;
}

NZ_Tango
11-26-2002, 07:37 AM
Ah thanks Glenngv, that should work well.