I have a javascript array dataArray which I want to push into a new array newArray. Except I don't want newArray[0] to be dataArray. I want to push in all the values into the new array:

var newArray = [];

newArray.pushValues(dataArray1);
newArray.pushValues(dataArray2);
// ...

or even better:

var newArray = new Array (
   dataArray1.values(),
   dataArray2.values(),
   // ... where values() (or something equivalent) would push the individual values into the array, rather than the array itself
);

So now the new array contains all the values of the individual data arrays. Is there some shorthand like pushValues available so I don't have to iterate over each individual dataArray, adding the values 1 by 1?

14 Answers 14

up vote 877 down vote accepted

Use the concat function, like so:

var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);

The value of newArray will be [1, 2, 3, 4] (arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).

  • 4
  • 66
    Slow though: jsperf.com/concat-vs-push-apply/10 – w00t Aug 20 '12 at 19:42
  • 8
    I agree that performant execution is very nice. BUT isn't concat exactly for that purpose to concat to arrays? So it should be standard. Or is there other better things to do with concat? And it might be slow only because of bad implementation of the JS engine of the browser or wherever you're using it in? It might be fixed one day. I would choose code maintainability over hacky speed optimizations. Hmm .... – Bitterblue Jun 10 '16 at 9:04
  • Also I just benchmarked the situation: concat vs. push.apply. Google Chrome: fast (concat = winner), Opera: fast (concat = winner), IE: slower (concat = winner), Firefox: slow (push.apply = winner, yet 10 times slower than Chrome's concat) ... speak of bad JS engine implementation. – Bitterblue Jun 10 '16 at 9:25
  • How is concatenating two arrays the accepted answer for how to push one into another?! Those are two different operations. – kaqqao Mar 6 '17 at 19:18

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 https://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]);
    }
};

I will add one more "future-proof" reply

In ECMAScript 6, you can use the spread operator:

var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);

Spread operator is not yet included in all major browsers. For the current compatibility, see this (continuously updated) compatibility table.

You can, however, use spread operator with Babel.js.

  • 3
    You can also use the spread operator if you are using TypeScript. If you target ES5, it will compile to newArray.apply(newArray, dataArray1). – AJ Richardson Feb 26 '16 at 21:28
  • 2
    Note: if you need the result in a third array (thus not modifying arr1, as the initial question seemed to require), you can do newArray = [...arr1, ...arr2] – dim Sep 29 '17 at 19:42

Found an elegant way from MDN

var vegetables = ['parsnip', 'potato'];
var moreVegs = ['celery', 'beetroot'];

// Merge the second array into the first one
// Equivalent to vegetables.push('celery', 'beetroot');
Array.prototype.push.apply(vegetables, moreVegs);

console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']

Or you can use the spread operator feature of ES6:

let fruits = [ 'apple', 'banana'];
const moreFruits = [ 'orange', 'plum' ];

fruits.push(...moreFruits); // ["apple", "banana", "orange", "plum"]
var a=new Array('a','b','c');
var b=new Array('d','e','f');
var d=new Array('x','y','z');
var c=a.concat(b,d)

Does that solve your problem ?

The following seems simplest to me:

var newArray = dataArray1.slice();
newArray.push.apply(newArray, dataArray2);

As "push" takes a variable number of arguments, you can use the apply method of the push function to push all of the elements of another array. It constructs a call to push using its first argument ("newArray" here) as "this" and the elements of the array as the remaining arguments.

The slice in the first statement gets a copy of the first array, so you don't modify it.

Update If you are using a version of javascript with slice available, you can simplify the push expression to:

newArray.push(...dataArray2)
  • Is also mentioned here at MDN as an example for "Merging two arrays" – Wilt Apr 27 at 15:48

With JavaScript ES6, you can use the ... operator as a spread operator which will essentially convert the array into values. Then, you can do something like this:

var myArray = [1,2,3,4,5];
var moreData = [6,7,8,9,10];

myArray = [
  ...myArray,
  ...moreData,
];

While the syntax is concise, I do not know how this works internally and what the performance implications are on large arrays.

  • 1
    If you take a look at how babel converts it, you'll see that it should not be any slower than using Array.push.apply technique. – emil.c Dec 11 '17 at 9:19

The function below doesn't have an issue with the length of arrays and performs better than all suggested solutions:

function pushArray(list, other) {
    var len = other.length;
    var start = list.length;
    list.length = start + len;
    for (var i = 0; i < len; i++ , start++) {
        list[start] = other[i];
    }
}

unfortunately, jspref refuses to accept my submissions, so here they are the results using benchmark.js

        Name            |   ops/sec   |  ± %  | runs sampled
for loop and push       |      177506 |  0.92 | 63
Push Apply              |      234280 |  0.77 | 66
spread operator         |      259725 |  0.40 | 67
set length and for loop |      284223 |  0.41 | 66

where

for loop and push is:

    for (var i = 0, l = source.length; i < l; i++) {
        target.push(source[i]);
    }

Push Apply:

target.push.apply(target, source);

spread operator:

    target.push(...source);

and finally the 'set length and for loop' is the above function

There are a number of answers talking about Array.prototype.push.apply. Here is a clear example:

var dataArray1 = [1, 2];
var dataArray2 = [3, 4, 5];
var newArray = [ ];
Array.prototype.push.apply(newArray, dataArray1); // newArray = [1, 2]
Array.prototype.push.apply(newArray, dataArray2); // newArray = [1, 2, 3, 4, 5]
console.log(JSON.stringify(newArray)); // Outputs: [1, 2, 3, 4, 5]

If you have ES6 syntax:

var dataArray1 = [1, 2];
var dataArray2 = [3, 4, 5];
var newArray = [ ];
newArray.push(...dataArray1); // newArray = [1, 2]
newArray.push(...dataArray2); // newArray = [1, 2, 3, 4, 5]
console.log(JSON.stringify(newArray)); // Outputs: [1, 2, 3, 4, 5]

We have two array a and b. the code what did here is array a value is pushed into array b.

let a = [2, 4, 6, 8, 9, 15]

function transform(a) {
    let b = ['4', '16', '64']
    a.forEach(function(e) {
        b.push(e.toString());
    });
    return b;
}

transform(a)

[ '4', '16', '64', '2', '4', '6', '8', '9', '15' ]
  • Please don't just post code as an answer. Explain what the code does and how it solves the problem. – Patrick Hund Jun 7 '17 at 18:28

Here's the ES6 way

var newArray = [];
let dataArray1 = [1,2,3,4]
let dataArray2 = [5,6,7,8]
newArray = [...dataArray1, ...dataArray2]
console.log(newArray)

instead of push() function use concat function for IE. example,

var a=a.concat(a,new Array('amin'));

Тhis is a working code and it works fine:

var els = document.getElementsByTagName('input'), i;
var invnum = new Array();
var k = els.length;
for(i = 0; i < k; i++){invnum.push(new Array(els[i].id,els[i].value))}

Most simple:

var newArray = dataArray1.slice(0);
  • 1
    This does not cover the problem in the question: concatenating two arrays. – frasertweedale May 8 '15 at 9:40

protected by T J Jan 4 '16 at 17:12

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.