Creating a duplicate array or object in JavaScript without reference (managing its original state)
Some of the issues I faced while I was working on my project was on creating a duplicate array and modifying it, but the actual array also gets modified.
So for example if I have an array- say, this.orginalArray = [1,2,3,4];
and then I want an array with all the elements in this.orginalArray except the element at index 2. So,
I could do this:
let array = this.orginalArray;
array.splice(2,1);
so array becomes: [1,2,4].
but here, this.orginalArray will also be modified to [1,2,4];
this has caused a lot of issues and hence I learnt some of the workarounds that helped me resolve this. So below are the methods that you can adapt to avoid these kind of issues.
let array = Array.from(this.orginalArray)
let array = this.orginalArray.slice()
let array = […this.orginalArray]
OR
let copyArray = JSON.stringify(this.orginalArray);
array = JSON.parse(copyArray);
if it is an object, let copyObj = Object.assign({}, orginalObj)
If you have anymore ideas, or tips or suggestions, please add as a comment and let me know.
Thanks for reading!