Java Collections have a method to add all elements of another collection: addAll(Collection other)
.
What is the equivalent to do in place appending of javascript arrays?
We cannot use Array.concat
, because it creates a new array and leaves the original array untouched.
So, given two arrays, how b
to a
, how to append all elements of b
to a
in place (therefore c
also changes!):
var a = [1, 2, 3]; var b = ['foo', 'bar']; var c = a; // a.addAll(b); // so that `c` equals to [1, 2, 3, 'foo', 'bar']
The addAll() method of java. util. Collections class is used to add all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.
I'm occassionally irked by the fact that a collection of DOM elements (more formally called a NodeList ) can't be manipulated like an array, because it isn't one.
List addAll() Method in Java with Examples. This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator.
add is used when you need to add single element into collection. addAll is used when you want to add all elements from source collection to your collection.
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" ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With