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.
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.
You can use either the spread operator [... array1, ... array2] , or a functional way []. concat(array1, array2) to merge 2 or more arrays.
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.
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.
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])
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