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:
>>> a.push.apply(a, b)
click below button to copy the code. By JavaScript tutorial team
or perhaps, if we think it's clearer:
>>> Array.prototype.push.apply(a,b)
click below button to copy the code. By JavaScript tutorial team
Solution 2:
For those that simply searched for "javascript array extend" and got here, we can very well use Array.concat.
var a = [1, 2, 3];
a = a.concat([5, 4, 3]);
click below button to copy the code. By JavaScript tutorial team
- 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:
const a = [1, 2, 3];
const b = [...a, 5, 4, 3];
click below button to copy the code. By JavaScript tutorial team
Solution 3:
If we want to use jQuery, there is $.merge()
Example:
a = [1, 2];
b = [3, 4, 5];
$.merge(a,b);
click below button to copy the code. By JavaScript tutorial team
Result:
a = [1, 2, 3, 4, 5]
click below button to copy the code. By JavaScript tutorial team
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:
Array.prototype.append = function(array)
{
this.push.apply(this, array)
}
click below button to copy the code. By JavaScript tutorial team
and use it like this
a = [1,2]
b = [3,4]
a.append(b)
click below button to copy the code. By JavaScript tutorial team
Solution 5:
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() //
click below button to copy the code. By JavaScript tutorial team
But despite being uglier it is not faster than push.apply
, at least not in Firefox 3.0. Posted for completeness sake.