136

This question is an exact duplicate of:
How to append an array to an existing JavaScript Array?

How do you append an array to another array in JavaScript?

Other ways that a person might word this question:

  • Add an array to another
  • Concat / Concatenate arrays
  • Extend an array with another array
  • Put the contents of one array into another array

I spent some time looking for the answer to this question. Sometimes the simplest ones like these are the hardest to find answers to, so I am adding the question here hopefully with plenty of key words and phrases as per this blog post. Please feel free to answer this question with any other helpful information or edit the key words and phrases below.

Community
  • 1
  • 1
Chris Dutrow
  • 48,402
  • 65
  • 188
  • 258
  • 8
    It *is* OK to answer your own question, it is *not* OK to put answer directly in the question itself. Please remove answer from the question, post it as an answer and self-accept it :-). Also, others might provide even better answers, outscoring yours ;-). – Tomasz Nurkiewicz Mar 10 '12 at 22:44
  • 2
    But questions should be answered with an answer, not in the question. But it's a [dupe](http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array) anyway, [multiple times](http://stackoverflow.com/questions/5080028/what-is-the-most-efficient-way-to-concatenate-n-arrays-in-javascript), so I'm voting to close. Searching for "javascript concatenate arrays" turned up quite a few hits anyway. – Dave Newton Mar 10 '12 at 22:44
  • @Dave Newton: The problem is that if you don't know to use the keyword "concatenate", then you won't find anything. I think that is why it is difficult to find answers to the easier questions. Experts are like "just type this!". But people looking for answer to that question will not know to search using the keywords that an expert knows. – Chris Dutrow Mar 10 '12 at 22:49
  • @Tomasz Nurkiewicz: I can move the answer to the answers section. However, I wanted to give other people an opportunity to answer the question and get points as opposed to generating points for myself. – Chris Dutrow Mar 10 '12 at 22:51
  • @DutrowLLC "Append javascript array" returned mostly the same ones, including [this one](http://stackoverflow.com/questions/351409/newbie-javascript-appending-to-array) and [one I posted above](http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array); append was your title/terminology. I'm somewhat sympathetic, but searching on either Google or SO would have turned those up. If I type your title in to a new question, it shows the latter of the above two as well. – Dave Newton Mar 10 '12 at 23:26
  • @Dave Newton - It took me a while to find the answer to this question. I tried several searches. I mostly found the answers to more complex questions. One of the questions you linked to is a duplicate, but the other one is not. You probably did a quick search and found some things that looked similar and then voted to close. Remember that you are different from the kind of person who will benefit from this question in two ways: 1) You don't need to know the answer. 2) You already know the answer. Because you know the answer it is much easier for you to find the answer. – Chris Dutrow Mar 11 '12 at 00:01
  • @DutrowLLC As I said, I'm sympathetic. They are duplicates, however, merely providing multiple answers to the same question. I did multiple searches both here, and on Google, using a wider range of searches than I enumerated, using both specific and general language. The bottom line is that on SO, when a question is a duplicate, it will be closed, but (generally) not deleted, allowing as close to a single point of reference as possible, rather than having multiple sets of answers, which is more confusing than anything else. – Dave Newton Mar 11 '12 at 00:08
  • @Dave Newton Oh I see what you are saying. I thought you meant the question shouldn't be there in the first place or should be deleted. Flagging it as a duplicate but not removing is the correct way to handle this situation. People will still be able to find the answer to this question more easily. – Chris Dutrow Mar 11 '12 at 00:16
  • @DutrowLLC No worries :) – Dave Newton Mar 11 '12 at 01:05

1 Answers1

173

If you want to modify the original array instead of returning a new array, use .push()...

array1.push.apply(array1, array2);
array1.push.apply(array1, array3);

I used .apply to push the individual members of arrays 2 and 3 at once.

or...

array1.push.apply(array1, array2.concat(array3));

To deal with large arrays, you can do this in batches.

for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
    array1.push.apply(array1, to_add.slice(n, n+300));
}

If you do this a lot, create a method or function to handle it.

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);

Object.defineProperty(Array.prototype, "pushArrayMembers", {
    value: function() {
        for (var i = 0; i < arguments.length; i++) {
            var to_add = arguments[i];
            for (var n = 0; n < to_add.length; n+=300) {
                push_apply(this, slice_call(to_add, n, n+300));
            }
        }
    }
});

and use it like this:

array1.pushArrayMembers(array2, array3);

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);

Object.defineProperty(Array.prototype, "pushArrayMembers", {
    value: function() {
        for (var i = 0; i < arguments.length; i++) {
            var to_add = arguments[i];
            for (var n = 0; n < to_add.length; n+=300) {
                push_apply(this, slice_call(to_add, n, n+300));
            }
        }
    }
});

var array1 = ['a','b','c'];
var array2 = ['d','e','f'];
var array3 = ['g','h','i'];

array1.pushArrayMembers(array2, array3);

document.body.textContent = JSON.stringify(array1, null, 4);
  • 7
    this way sucks and doesnt work for >500 ish element arrays – jordan Nov 20 '13 at 17:33
  • 10
    tl;dr: `array1 = [].concat(array1, array2, array3 /*, .. */);` is better – Alex Dec 04 '14 at 18:12
  • 1
    @Alex: Fails to modify the original array, which is what the question is asking. And it's not better to use `[].concat(...` when you already have an array. It should be `array1.concat(array2, array3)`. –  Dec 04 '14 at 18:26
  • @squint point, but `array1.concat(array2, array3)` don't do it either as `concat()` returns a new array. – Alex Dec 05 '14 at 16:11
  • If I wouldn't need to edit the array itself and is fine with reassigning the var, I'd use `[].concat(..)` – Alex Dec 05 '14 at 16:12
  • @Alex: Sure, but that would be a different situation from the one described in the question. Just trying to stay on topic. Still, why create an empty array? That part doesn't make sense when you can just do `array1.concat(array2, array3)`. The `.concat()` method doesn't mutate the original. –  Dec 07 '14 at 00:24
  • I just think it's more readable and clear that you don't mutate `array1` (as _some_ array method in js mutates the array, and some doesn't) – Alex Dec 09 '14 at 11:55
  • This jsperf shows that just looping and adding each element with push is the fastest (at least with my version of Chrome and OS). It doesn't have any stack overflow problems either. https://jsperf.com/array-prototype-push-apply-vs-concat/20 – bmacnaughton Oct 26 '15 at 16:26
  • Seems the upper limit to `push.apply` is 125510 in Chrome (56.0.2924.87 (64-bit)): (`a = []; a.length = 125510; test.apply(null, a);`). 125511 will trigger an overflow error. – James Wilkins May 15 '17 at 16:02
  • this solution is so smart! – shaosh Jul 08 '17 at 13:31
  • 2
    I like the answer from the duplicate question best: https://stackoverflow.com/questions/1374126/how-to-extend-an-existing-javascript-array-with-another-array-without-creating#answer-1374131 – Bret Royster Aug 17 '20 at 13:25