Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I merge two arrays to create one array in JavaScript?

Tags:

javascript

Imagine I've got two arrays in JavaScript:

var geoff = ['one', 'two'];
var degeoff = ['three', 'four'];

How do I merge the two arrays, resulting in an array like this?

var geoffdegeoff = ['one', 'two', 'three', 'four'];
like image 878
Paul D. Waite Avatar asked Aug 26 '09 16:08

Paul D. Waite


2 Answers

var geoffdegeoff = geoff.concat(degeoff);
like image 81
molf Avatar answered Oct 14 '22 12:10

molf


I stumbled across this and thought to add an additional way.

note: I see you want to create a third new var.

.concat is good, but you have to create a new array (unless you override the orig).

How about if you want to merge/combine array "second" into array "first".

Here is a nifty way.

// using apply
var first = ['aa','bb','cc'];
var second = ['dd','ee'];
first.push.apply(first, second);
first;

or

Array.prototype.push.apply(first, second); 
first;
like image 30
james emanon Avatar answered Oct 14 '22 13:10

james emanon