javascript tutorial - [Solved-5 Solutions] Extend an existing javascript array with another array - javascript - java script - javascript array
Problem:
How to extend existing javascript array with another array without creating new array?
Solution 1:
The .push method can take multiple arguments, so by using .apply to pass all the elements of the second array as arguments to .push, we can get the result we want:
or perhaps, if we think it's clearer:
Solution 2:
For those that simply searched for "javascript array extend" and got here, we can very well use Array.concat.
- Concat will return a copy the new array, as thread starter didn't want. But we might not care (certainly for most kind of uses this will be fine).
- There's also some nice ES6 sugar for this in the form of the spread operator:
Solution 3:
If we want to use jQuery, there is $.merge()
Example:
Result:
Solution 4:
We like the a.push.apply(a, b)
method described above, and if we want we can always create a library function like this:
and use it like this
Solution 5:
It is possible to do it using splice()
:
But despite being uglier it is not faster than push.apply
, at least not in Firefox 3.0. Posted for completeness sake.