Reputation: 992
I want to unshift on a copy of the array, but the original array modifies too. Why is that?
var array1 = [1, 2, 3]
var array2 = array1
array2.unshift(4, 5)
console.log(array1)
console.log(array2)
Upvotes: 0
Views: 283
Reputation: 5947
Use spread operator( ... )
to make second array. It will make a new array with new reference. And then perform your task.
var array1 = [1, 2, 3];
var array2 = [...array1];
array2.unshift(4, 5);
console.log(array1);
console.log(array2);
Upvotes: 2
Reputation: 20039
Try using Array.from()
var array1 = [1, 2, 3]
var array2 = Array.from(array1)
array2.unshift(4, 5)
console.log(array1)
console.log(array2)
Upvotes: 2