Creating a duplicate array or object in JavaScript without reference (managing its original state)

Najiya Nasrin
1 min readMay 22, 2021

--

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!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Najiya Nasrin
Najiya Nasrin

Written by Najiya Nasrin

Simple. Fun. Friendly. Developer. Enthusiast.

No responses yet

Write a response