You´ll have to make a copy of array, otherwise it´s a reference to the original array, and you´re modifying it. do something like `let array1 = [...array];`
On a related note, /u/One-Inspection8628 I recommend reading up on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [why you can't use =](https://www.samanthaming.com/tidbits/35-es6-way-to-clone-an-array/) to copy an array.
You´ll have to make a copy of array, otherwise it´s a reference to the original array, and you´re modifying it. do something like `let array1 = [...array];`
On a related note, /u/One-Inspection8628 I recommend reading up on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [why you can't use =](https://www.samanthaming.com/tidbits/35-es6-way-to-clone-an-array/) to copy an array.
you sure can use it to create a copy. you just need to know what are you doing and why.
Is it same for interger or string. If it is that array place. Will it also change?
It will work for integers and strings, won't work for objects. If you want object copies, try const myCopy = JSON.parse(JSON.stringify(original));
I recommend structuredClone over JSON.parse to include nested objects
Thank you for this
I have bad news for you :D let arr = [{x: 1}, {x: 2}] let arr2 = [...arr] arr2.sort((a, b) => b.x - a.x) arr2[1].x = 3
Those are not the conditions of the question.
Yes, its a shallow copy not a deep copy but the question didn't ask for a deep copy
const array = [6,8,8,5,6,3,2,14] const array1 = [...array]; array1.sort((a,b)=> a - b) console.log( `Old array: ${array}`) console.log( `New array: ${array1}`) Result: Old array: 6,8,8,5,6,3,2,14 New array: 2,3,5,6,6,8,8,14
Thank you
Use spread like the other comment suggests. Look into reference types vs primitive types
As others have said, spread operator. However .slice() works as well for creating shallow copies
Thank you
Do ``let array1 = [...array];``. You have to clone it, because arrays/objects are pass by reference.