Categories
append arrays javascript

How to append something to an array?

2891

How do I append an object (such as a string or number) to an array in JavaScript?

    5083

    Use the Array.prototype.push method to append values to the end of an array:

    // initialize array
    var arr = [
      "Hi",
      "Hello",
      "Bonjour"
    ];
    
    // append new value to the array
    arr.push("Hola");
    
    console.log(arr);

    You can use the push() function to append more than one value to an array in a single call:

    // initialize array
    var arr = ["Hi", "Hello", "Bonjour", "Hola"];
    
    // append multiple values to the array
    arr.push("Salut", "Hey");
    
    // display all values
    for (var i = 0; i < arr.length; i++) {
      console.log(arr[i]);
    }

    Update

    If you want to add the items of one array to another array, you can use firstArray.concat(secondArray):

    var arr = [
      "apple",
      "banana",
      "cherry"
    ];
    
    // Do not forget to assign the result as, unlike push, concat does not change the existing array
    arr = arr.concat([
      "dragonfruit",
      "elderberry",
      "fig"
    ]);
    
    console.log(arr);

    Update

    Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use Array.prototype.unshift for this purpose.

    var arr = [1, 2, 3];
    arr.unshift(0);
    console.log(arr);

    It also supports appending multiple values at once just like push.


    Update

    Another way with ES6 syntax is to return a new array with the spread syntax. This leaves the original array unchanged, but returns a new array with new items appended, compliant with the spirit of functional programming.

    const arr = [
      "Hi",
      "Hello",
      "Bonjour",
    ];
    
    const newArr = [
      ...arr,
      "Salut",
    ];
    
    console.log(newArr);

    1

    • 171

      Note the return value of .push is not the array (or a new one, like .concat), but an integer representing the array’s new length.

      – Jay

      Jan 10, 2016 at 0:09

    1100

    If you’re only appending a single variable, then push() works just fine. If you need to append another array, use concat():

    var ar1 = [1, 2, 3];
    var ar2 = [4, 5, 6];
    
    var ar3 = ar1.concat(ar2);
    
    alert(ar1);
    alert(ar2);
    alert(ar3);

    The concat does not affect ar1 and ar2 unless reassigned, for example:

    var ar1 = [1, 2, 3];
    var ar2 = [4, 5, 6];
    
    ar1 = ar1.concat(ar2);
    alert(ar1);

    There is a lot of great information on JavaScript Reference.

    9

    • 175

      Just making sure people catch the var ar3 = ar1.concat(ar2); part. ar1.concat(ar2) does not save the values into ar1. You have to catch it by assigning it to ar3 or back to ar1, such as: ar1 = ar1.concat(ar2);

      Jul 12, 2013 at 22:47

    • 38

      I’d say this is the wrong answer actually. The question was How do I append to an array in JavaScript?, but concat actually creates a new array. That is an important difference! Instead I’d say the answer below by Omnimike is actually the best one: Use Push.apply to push a whole array to an existing array without creating a new one.

      Sep 18, 2015 at 13:09

    • @StijndeWitt you can still append without creating a new array, as stated in the previous comment ar1 = ar1.concat(ar2); will append to ar1

      Apr 1, 2016 at 1:30

    • 3

      @cameronjonesweb Actually, what it does is create a new array with the same contents as ar1, append ar2 and then return the new array. Just leave out the assignment part (ar1 = ...) from that line of code and you’ll see that the original ar1 did not in fact change. If you want to avoid making a copy, you’ll need push. Don’t believe me, believe the docs: “The concat() method returns a new array” First sentence in the docs for concat.

      Apr 3, 2016 at 13:26

    • @StijndeWitt You’re right. But, a different way to look at it though, .push only works well in adding single variables/objects, but will however mess up when it comes to appending Arrays, which ar2 above is anyways. The result of .push in the scenario will be = [ar1, [ar2]]. .concat solves that problem, but with sacrifice of speed and a new array created. To use .push properly in array appends, loop out the contained element first and push each. ar2.forEach(each => { ar1.push(each); });

      – Ade

      Apr 7, 2018 at 18:29


    421

    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 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;
        }
    }
    

    7

    • 9

      The question is if .length is a stored value or is calculated when being accessed, since if the latter one is true then it might be that using a simple variable (such as j) as the index value might be even faster

      – yoel halb

      Aug 15, 2012 at 18:55

    • 4

      Would love to see concat() in the same test!

      – Justin

      Apr 30, 2013 at 0:10

    • 2

      I wonder how much this has changed in the past four years. (jsperf would be handy right now.)

      May 26, 2014 at 20:07


    • 8

      This type of benchmarking is interesting, but ironically not very helpful in making apps faster. The rendering loop is by far much much more expensive during any cycle. In addition these internals of the JS language are continuously being optimized by browser developers. Thats the reason for my downvote, not the interestingness of this answer. If you want faster apps, benchmark first and see what to change – 99 out of 100 times it won’t be an issue like this test shows. Often its poor developer JS/CSS – not browser internals that is making it slow.

      Sep 25, 2014 at 21:59


    • 8

      I agree with LessQuesar in sticking to the builtins whenever possible. Not that micro-optimization is bad in itself, but he’s right that browsers are always improving their engine speed. Case in point: as of this writing, the per-browser performance is nearly identical for all the techniques listed above. Meaning a lot of fuss a few years ago for such a small gain, when now there is no gain.

      – Beejor

      Aug 13, 2015 at 0:35