9

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'];

2 Answers 2

15
var geoffdegeoff = geoff.concat(degeoff);
Sign up to request clarification or add additional context in comments.

Comments

3

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;

7 Comments

Array.prototype == [] :)
I get what you are saying, but by passing in "first" as "this", we are changing/applying the second in place. I hope I get what you mean. lol.
I don't think you actually got my point; [].push.apply(first, second) is what I mean :)
This will be useful for big arrays, whereby truly appending data prevents a full array copy.
@Jack: While the substitution is valid in this case, Array.prototype != [].
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.