Languages

JavaScript - what is the equivalent of Java `Collection.addAll` for js arrays?

0 points
Asked by:
Wiktor-Sribiew
860

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
Answered by:
Wiktor-Sribiew
860

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

  1. Array.prototype.push() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join