Reverse array after assigning to another array

Hi, I have created a new array by assigning an array to the new array and only reversed the new array. However, I see that the original array is also changed. Does that mean to copy an array to a new array so that I can keep the original array, I must use slice() and cannot just assigned it with a β€œ=”?

let str="one";
 let arr1 = str.toLowerCase();
 arr1 = arr1.split("");
 let arr2 = arr1.filter(x=>x.match(/[\w\d]/g));
 let arr3 = arr2;

Thank you.

This does not create a new array. Instead, it creates a reference to the same array which arr2 represents. There are many methods to create a shallow copy of an array (i.e. slice, spread operator)

1 Like

You can create a new a array a couple of other ways. Splice is one way, you could also use the spread operator.

let arr3 = [...arr2]

You might find this useful, I did.

1 Like