Friday, February 5, 2010

Case insensitive sorting of Arrays in Javascript

Let me Assume elementArr as a javascript array. Then the following function, will sort the contents of the array in alphabetical order and case insensitive fashion and will work fine with IE6+ and Firefox. Not yet tested in Safari and Opera.


        elementArr.sort(function(x,y){
             var a = String(x).toUpperCase();
             var b = String(y).toUpperCase();
            if (a > b)     {
                return 1
            }    else  if (a < b) {
                return -1
            }    else    {   
                return 0;
            }   
        });


If the contents of the array are say [a,B,A,z,e,C], then the resultant array shall be some thing like this, [a,A,B,C,e,z]

Hope this helps :)

2 comments:

  1. There is a weak spot in your script. Try sorting aaAAaaaAaaAABbcc - I bet you you will have all As messed up still.

    Michael

    ReplyDelete
  2. Hi Michael, Happy that you mentioned it. I knew it all along. My idea was to share the concept with this "weak spot" you have mentioned :)

    At first I was a little confused about the part of your comment that says "you will have all As messed up still". I tried the following and I think I understood it good. Just a guess again

    I split your string into an array

    x=["a","a","A","A","a","a","a","A","a","a","A","A","B","b","c","c "].sort(function(x,y){
    var a = String(x).toUpperCase();
    var b = String(y).toUpperCase();
    if (a > b) {
    return 1
    } else if (a < b) {
    return -1
    } else {
    return 0;
    }
    });

    alert (x)

    And i got an alert saying "a,a,A,A,a,a,a,A,a,a,A,A,B,b,c,c".

    I believe this is what you mean by having all 'A's messed up still. :)

    I intented to do something like this any way and afterall, the title says "Case insensitive sorting of Arrays in Javascript" isn't it ? :)

    Let me know if I have messed up with my understanding of your comment as well :P

    ReplyDelete