Append an array to another array in JavaScript [duplicate]
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.
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);