/    Sign up×
Community /Pin to ProfileBookmark

Array is getting reduced when using promises and for loop

Dear all,
I am declaring an array 1 and aray 2 as shown below. I am using promise and then block. In the then block I am removing each element from array1 and it is automatically removing elements in array2 as well.
How can I keep array2 same as it is, but I should remove all the elements from array1 in th for loop. Please advice or share your ideas. Thank you for your support and help.

================================================
var arr1=[1,2,3,4];
var arr2=arr1;
var Length=arr1.length
let promise = new Promise(resolve =>{
resolve(arr2);

});

promise.then((result)=>{

for(var i=0;i<Length;i++)
{
arr1.shift();
console.log(arr2);
}

});

================================================

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumMar 06.2020 — The reason is not that you are using a promise but by this line of code:

`var arr2=arr1;`

you do not create a copy of arr1 but instead a reference to arr1 is assigned to the variable arr2. Therefore each action performed on arr2 affects arr1 or vice versa. In order to fix this google for "javascript clone array".
Copy linkTweet thisAlerts:
@NR2authorMar 06.2020 — Thank you so much for your reply. It is working with "javascript clone array".
×

Success!

Help @NR2 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...