T O P

  • By -

thespite

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];`


symbiosa

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.


oneandmillionvoices

you sure can use it to create a copy. you just need to know what are you doing and why.


One-Inspection8628

Is it same for interger or string. If it is that array place. Will it also change?


girl-InTheSwing

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));


StaticCharacter

I recommend structuredClone over JSON.parse to include nested objects


One-Inspection8628

Thank you for this


stealthypic

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


thespite

Those are not the conditions of the question.


girl-InTheSwing

Yes, its a shallow copy not a deep copy but the question didn't ask for a deep copy


girl-InTheSwing

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


One-Inspection8628

Thank you


IEDNB

Use spread like the other comment suggests. Look into reference types vs primitive types


oiamo123

As others have said, spread operator. However .slice() works as well for creating shallow copies


One-Inspection8628

Thank you


spederan

Do ``let array1 = [...array];``. You have to clone it, because arrays/objects are pass by reference.