There doesn't seem to be a way to extend an existing JavaScript array with another array, i.e. to emulate Python's extend
method.
I want to achieve 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
).
Note: This is not a duplicate of How to append something to an array? -- the goal here is to add the whole contents of one array to the other, and to do it "in place", i.e. without copying all elements of the extended array.
The
.push
method can take multiple arguments, so by using.apply
to pass all the elements of the second array as arguments to.push
, you can get the result you want:Or perhaps, if you think it's clearer:
If your browser supports ECMAScript 6, you can use the spread operator, which is more compact and elegant:
Please note that all these solutions will fail with a stack overflow error if array
b
is too long (trouble starts at about 100,000 elements, depending on the browser). If you cannot guarantee thatb
is short enough, you should use a standard loop-based technique described in the other answer.Another solution to merge more than two arrays
Then call and print as:
Output will be:
Array [1, 2, 3, 4, 5, 6, 7]
Update 2018: A better answer is a newer one of mine:
a.push(...b)
. Don't upvote this one anymore, as it never really answered the question, but it was a 2015 hack around first-hit-on-Google :)For those that simply searched for "JavaScript array extend" and got here, you can very well use
Array.concat
.Concat will return a copy the new array, as thread starter didn't want. But you might not care (certainly for most kind of uses this will be fine).
There's also some nice ECMAScript 6 sugar for this in the form of the spread operator:
(It also copies.)
The answer is super simple.
Concat acts very similarly to JavaScript string concatenation. It will return a combination of the parameter you put into the concat function on the end of the array you call the function on. The crux is that you have to assign the returned value to a variable or it gets lost. So for example
I feel the most elegant these days is:
The MDN article on the spread operator mentions this nice sugary way in ES2015 (ES6):
Do note that
arr2
can't be huge (keep it under about 100 000 items), because the call stack overflows, as per jcdude's answer.I can see very nice answers, and it all depends on your array size, your requirement and goal. It can be done in different ways.
I suggest using a JavaScript for loop:
console.log(a)
output will beThen you can make your own function:
console.log(extendArray(a, b));
output will be