EN
JavaScript - what is the equivalent of Java `Collection.addAll` for js arrays?
1
answers
0
points
In Java Collections have addAll() method to add all elements of another collection.
Is there any equivalent for appending in place to JavaScript arrays?
I can't use concat(), because it creates a new array and leaves the original array unchanged.
My code:
const array1 = [1, 2, 3];
const array2 = ['a', 'b', 'c'];
const array3 = array1;
// I need:
// array1.addAll(array2);
// so that array3 equals to [1, 2, 3, 'a', 'b', 'c']
I need to append all elements of array2 to array1 in place (therefore array3 also changes).
1 answer
0
points
You can use push() method to add multiple elements to the end of an array.
ES6+ solution
Using push() with spread operator(...) to add multiple elements.
// ONLINE-RUNNER:browser;
const array1 = [1, 2, 3];
const array2 = ['a', 'b', 'c'];
const array3 = array1;
array1.push(...array2);
console.log(array1); // [1, 2, 3, 'a', 'b', 'c'];
For older versions of JavaScript
// ONLINE-RUNNER:browser;
var array1 = [1, 2, 3];
var array2 = ['a', 'b', 'c'];
var array3 = array1;
Array.prototype.push.apply(array1, array2);
console.log(array1); // [1, 2, 3, 'a', 'b', 'c'];
or:
// ONLINE-RUNNER:browser;
var array1 = [1, 2, 3];
var array2 = ['a', 'b', 'c'];
var array3 = array1;
array1.push.apply(array1, array2);
// or shorter:
// [].push.apply(array1, array2);
console.log(array1); // [1, 2, 3, 'a', 'b', 'c'];
References
0 comments
Add comment