Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
    

10 Answers 10

up vote 444 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).

share|improve this answer
3  
44  
Slow though: jsperf.com/concat-vs-push-apply/10 – w00t Aug 20 '12 at 19:42
    
The answer below is much more detailed, I agree- wish I could assign that as the correct answer. – WiseGuyEh Feb 22 '13 at 15:38
2  
Voted down because it's gobs slower than .push.apply and attention should go to the @tim-down answer – JohnAllen Dec 15 '15 at 2:45
    
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 at 9:04

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]);
    }
};
share|improve this answer
3  
note: newArray.push.apply(newArray, dataArray1); gives the same as Array.prototype.push.applay(newArray,dataArra1); – user669677 Jul 5 '13 at 11:02
1  
push.apply whas exacly what I was looking for, thx – Jaak Kütt Nov 9 '13 at 17:09
    
Much better, +1. – Jonatas Walker Sep 30 '15 at 15:09
    
Thank you very much for this solution! may I ask if there is something reverse? like removing an entire array from another? – Simona Adriani Sep 7 at 13:31

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.

share|improve this answer
1  
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 at 21:28
    
MDN says it is spread operator: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Gabriel Southern May 24 at 22:55
    
...I don't care, frankly. Edit away :) – Karel Bílek May 25 at 12:50
1  
@KarelBílek you had the correct terminology in your original answer, my edit was simply a revision to what you wrote in the first place. – Gabriel Southern Jun 1 at 17:11

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"]
share|improve this answer
1  
This is a great simple solution that I like because you aren't referencing a new array in vegetables like you would if you used the .concat method, and no loop is required. – Kevin Beal Mar 10 at 22:01
    
brilliant, you are genius... – hhsadiq May 27 at 13:51
    
this clearly should be the accepted answer – MatteoSp Aug 9 at 18:46
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 ?

share|improve this answer
    
please use comments to ask questions to OP – T J Jan 4 at 17:15

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.

share|improve this answer

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.

share|improve this answer

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

var a=a.concat(a,new Array('amin'));
share|improve this answer

Т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))}
share|improve this answer

Most simple:

var newArray = dataArray1.slice(0);
share|improve this answer
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 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.