Provided your arrays are not huge (see caveat below), you can use the push()
method of the array to which you wish to append values. push()
can take multiple parameters so you can use its apply()
method to pass the array of values to be pushed as a list of function parameters. This has the advantage over using concat()
of adding elements to the array in place rather than creating a new array.
However, it seems that for large arrays (of the order of 100,000 members or more), this trick can fail. For such arrays, using a loop is a better approach. See http://stackoverflow.com/a/17368101/96100 for details.
var newArray = [];
newArray.push.apply(newArray, dataArray1);
newArray.push.apply(newArray, dataArray2);
You might want to generalize this into a function:
function pushArray(arr, arr2) {
arr.push.apply(arr, arr2);
}
... or add it to Array
's prototype:
Array.prototype.pushArray = function(arr) {
this.push.apply(this, arr);
};
var newArray = [];
newArray.pushArray(dataArray1);
newArray.pushArray(dataArray2);
... or emulate the original push()
method by allowing multiple parameters using the fact that concat()
, like push()
, allows multiple parameters:
Array.prototype.pushArray = function() {
this.push.apply(this, this.concat.apply([], arguments));
};
var newArray = [];
newArray.pushArray(dataArray1, dataArray2);
Here's a loop-based version of the last example, suitable for large arrays and all major browsers, including IE <= 8:
Array.prototype.pushArray = function() {
var toPush = this.concat.apply([], arguments);
for (var i = 0, len = toPush.length; i < len; ++i) {
this.push(toPush[i]);
}
};