Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'] 
like image 765
Michael_Scharf Avatar asked Feb 26 '16 17:02

Michael_Scharf


People also ask

What is collections addAll in Java?

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.

Is a collection an array JavaScript?

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.

What is addAll in list?

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.

What is the difference between ADD and addAll in list in Java?

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.


Video Answer


1 Answers

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" ] 
like image 170
madox2 Avatar answered Sep 22 '22 11:09

madox2