views:

366

answers:

4

There doesn't seem to be a way to expand a JavaScript Array with another Array, i.e. to emulate Python's extend method.

What I want to achieve is the following:

>>> a = [1, 2]
[1, 2]
>>> b = [3, 4, 5]
[3, 4, 5]
>>> SOMETHING HERE
>>> a
[1, 2, 3, 4, 5]

I know there's a a.concat(b) method, but it creates a new array instead of simply extending the first one. I'd like an algorithm that works efficiently when a is significantly larger than b (i.e. one that does not copy a).

+9  A: 

The best I came up with so far is:

>>> a.push.apply(a, b)

but it feels a little like a hack. Any other suggestions?

DzinX
This is exactly how you do it. Why does it feel like a hack?
kangax
I think this is your best bet. Anything else is going to involve iteration or another exertion of apply()
Peter Bailey
+1  A: 

Did u try it by using splice method ?

rty
A: 

concat will be the one you want:

>>> a = [1, 2]
[1, 2]
>>> b = [3, 4, 5]
[3, 4, 5]
>>> a = a.concat(b)
>>> a
[1, 2, 3, 4, 5]

Edit: just saw your note about concat. In that case your a.push.apply(a, b) is going to be the most efficient.

McKAMEY
Did you even try to execute your code? It does not work, as concat does not modify array 'a'.
DzinX
you're right need to assign result back to to `a`
McKAMEY
Still it's not correct, as the OP requires the existing array to modified in place instead of creating a new one.
Imran
+1  A: 

It is possible to do it using splice():

b.unshift(b.length)
b.unshift(a.length)
Array.prototype.splice.apply(a,b) 
b.shift() // restore b
b.shift() //

But despite being uglier it is not faster than push.apply, at least not in Firefox 3.0. Posted for completeness sake.

Rafał Dowgird