Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
198
rated 0 times [  200] [ 2]  / answers: 1 / hits: 39590  / 8 Years ago, fri, february 26, 2016, 12:00:00

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']

More From » arrays

 Answers
123

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 ]

[#63142] Thursday, February 25, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cadendericki

Total Points: 482
Total Questions: 109
Total Answers: 103

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
cadendericki questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Wed, Jul 8, 20, 00:00, 4 Years ago
Thu, May 14, 20, 00:00, 4 Years ago
;