Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat arrays in JS in mutating way? [duplicate]

What is the best way to concat arrays in mutating way in JS? My problem:

var a = [1,2,3]
var b = a;
a = a.concat([4,5,6]) //<-- typical way of array concatenation in JS
console.log(a) //[1,2,3,4,5,6]
console.log(b) //[1,2,3] <-- I'd like it to be the same like a here

I can use some loop of course, but I wonder if there is some faster and cleaner way to achieve it.

like image 789
Karol Selak Avatar asked Aug 29 '17 22:08

Karol Selak


People also ask

Is array concat mutating?

prototype. concat() is used to merge two or more arrays. This method does not mutate the original array, but instead returns a new array populated with elements of all the arrays that were merged.

How do you concatenate arrays in JavaScript?

You can use either the spread operator [... array1, ... array2] , or a functional way []. concat(array1, array2) to merge 2 or more arrays.

Can we concat two arrays in JavaScript?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

How do you stop an array from mutating?

We can prevent mutation of objects and arrays using the Object. freeze() JavaScript function. We pass the desired object or array as an argument to this function, which later prevents any change to the object's or array's data.


1 Answers

push mutates an array, but it expects sequence of arguments, so we use apply:

var a = [1,2,3]
var b = a
a.push.apply(a, [4,5,6])
console.log(a) //=> [1, 2, 3, 4, 5, 6]
console.log(b) //=> [1, 2, 3, 4, 5, 6]

In ES6 you could use spread operator ...:

a.push(...[4, 5, 6])
like image 147
Danil Speransky Avatar answered Sep 20 '22 03:09

Danil Speransky