Tenzolinho
Tenzolinho

Reputation: 992

Perform unshift method on a copy of array

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

Answers (2)

Harun Or Rashid
Harun Or Rashid

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

User863
User863

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

Related Questions