What is the equivalent of Java `Collection.addAll` for JavaScript arrays?

You can use the apply method of Array.prototype.push():

var a = [1, 2, 3];
var b = ['foo', 'bar'];
Array.prototype.push.apply(a, b);
console.log(a); // Array [ 1, 2, 3, "foo", "bar" ]

or alternatively:

a.push.apply(a, b);
[].push.apply(a, b);

If you’re using ES6, it’s better to call .push() using the spread operator ... instead. This is more similar to Collection.addAll(...) because you can add values from any iterable object, not just arrays. It also allows you to add multiple iterables at once.

const a = [1, 2, 3];
const b = ['foo', 'bar'];
const c = new Set(['x', 'x', 'y', 'x']);
a.push(...b, ...c);
console.log(a); // Array [ 1, 2, 3, "foo", "bar", "x", "y" ]

Leave a Comment