Sunday, June 3, 2012

Appending to array


How do I append to an array in Javascript?



Source: Tips4all

6 comments:

  1. var arr = new Array(3); // Optional count -- it just controls the array's size
    arr[0] = "Hi";
    arr[1] = "Hello";
    arr[2] = "Bonjour";
    arr.push("Hola");
    for (var i = 0; i < arr.length; i++) {
    alert(arr[i]);
    };

    ReplyDelete
  2. If you're only appending a single variable, then your method works just fine. If you need to append another array, use concat(...) method of the array class:

    var ar1 = [1, 2, 3];
    var ar2 = [4, 5, 6];

    var ar3 = ar1.concat(ar2);

    alert(ar3);


    Will spit out "1,2,3,4,5,6"

    Lots of great info here

    ReplyDelete
  3. Some quick benchmarking (each test = 500k appended elements and the results are averages of multiple runs) showed the following:

    Firefox 3.6 (Mac):


    Small arrays: arr[arr.length] = b is faster (300ms vs. 800ms)
    Large arrays: arr.push(b) is faster (500ms vs. 900ms)


    Safari 5.0 (Mac):


    Small arrays: arr[arr.length] = b is faster (90ms vs. 115ms)
    Large arrays: arr[arr.length] = b is faster (160ms vs. 185ms)


    Google Chrome 6.0 (Mac):


    Small arrays: No significant difference (and Chrome is FAST! Only ~38ms !!)
    Large arrays: No significant difference (160ms)


    I like the arr.push() syntax better, but I think for my use I'd be better off with the arr[arr.length] version, at least in raw speed. I'd love to see the results of an IE run though.



    My benchmarking loops:

    function arrpush_small() {
    var arr1 = [];
    for (a=0;a<100;a++)
    {
    arr1 = [];
    for (i=0;i<5000;i++)
    {
    arr1.push('elem'+i);
    }
    }
    }

    function arrlen_small() {
    var arr2 = [];
    for (b=0;b<100;b++)
    {
    arr2 = [];
    for (j=0;j<5000;j++)
    {
    arr2[arr2.length] = 'elem'+j;
    }
    }
    }


    function arrpush_large() {
    var arr1 = [];
    for (i=0;i<500000;i++)
    {
    arr1.push('elem'+i);
    }
    }

    function arrlen_large() {
    var arr2 = [];
    for (j=0;j<500000;j++)
    {
    arr2[arr2.length] = 'elem'+j;
    }
    }

    ReplyDelete
  4. If arr is an array, and val is the value you wish to add use:

    arr.push(val);


    E.g.

    arr = ['a', 'b', 'c'];
    arr.push('d');
    console.log(arr);


    will log:

    ['a', 'b', 'c', 'd']

    ReplyDelete
  5. Is b a variable? If not, it probably needs quotes.

    Also, lots of good info on JavaScript push() method here.

    ReplyDelete
  6. Use concat:

    a = [1, 2, 3];
    b = [3, 4, 5];
    a = a.concat(b);


    a now contains all the elements, [1, 2, 3, 3, 4, 5].

    Reference: http://www.w3schools.com/jsref/jsref_concat_array.asp

    ReplyDelete