Wednesday, February 25, 2009

Manipulating Arrays in JavaScript

In my recent work I have had to do a lot of array manipulation in JavaScript. While doing this I learned a few tricks, that I did not want to forget and thought others might benefit from.

Some of these things are simple, but I include here for completeness. I welcome any feedback on any array tricks that you have learned.

  1. Adding to an array
    var array = [];
    array.push(5835);



  2. Deleting from an array
    var array =[];
    array.push(5835); // index of 0
    array.push(6835); // index of 1
    array.push(7835); // index of 2
    delete array[1];

    The resulting array would be [5835, 7835], but the indexes would still be [0,2]. JavaScript does not reorder the indexes to always be zero based.


  3. Array Looping
    Although you can loop through an array normally:

    for(var i = 0; i < array.length; i++) {
    alert("Index was " + i + ", value was " + array[i]);
    }

    You can get into trouble, if you are doing array manipulation like deleting. Like I stated in #2, there is no more index 1, so you would get a JavaScript error.
    Because of this I have become a fan of the following loop:

    for(var i in array) {
    if (typeof array[i] == "function") {
    continue;
    }
    alert("Index was " + i + ", value was " + array[i]);
    }

    A couple of things to note, first is the check to make sure the element is not a function. All arrays have a remove method inherent in them, so you need to skip that. Second, you will see that the indexes are indeed, 0, 2 and not 0, 1, if you use the dataset from #2.




More to come later...