When you sort an array in Javascript the array gets sorted into dictionary order. This means that ‘A’ is less than ‘a’ and gets sorted that way. If your array consists of both uppercase and lowercase entries then you probably want to sort alphabetically ignoring the case of the individual entries instead. We can change the way that the array sort method works by passing it a parameter identifying a function that contains the instructions on how to compare the entries.

To sort an array into order ignoring case add the following code (into the head section of your page is probably the most appropriate place):

function charOrdA(a, b){
a = a.toLowerCase(); b = b.toLowerCase();
if (a>b) return 1;
if (a <b) return -1;
return 0; }
function charOrdD(a, b)
a = a.toLowerCase(); b = b.toLowerCase();
if (a<b) return 1;
if (a >b) return -1;
return 0; }

We can now sort the array without the upper and lower case entries being sorted into different orders. The following example shows how:

charArray = new Array(‘c’,’A’,’z’,’f’,’D’);
charArray.sort( charOrdA );
document.write(‘Ascending : ‘ + charArray + ‘<br />’);
charArray.sort( charOrdD );
document.write(‘Descending : ‘ + charArray + ‘<br />’);