1. Home
  2. Computing & Technology
  3. JavaScript

Ignore Case Array Sort

Join the Discussion

Questions? Comments?

Related Resources

Numeric Sort Random Sort Date Sort

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 />');
Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.