For example I have listings
array :
[ { name: 'bob', price: '10' }, { name: 'jack', price: '12' } ]
I am trying to find lowest seller and work with it's data later.
I do var currentLowestSeller = listings[0];
Now currentLowestSeller
is:
{ name: 'bob', price: '10' }
Later I do changes is currentLowestSeller
but I don't want main listings
array to be changed.
I do currentLowestSeller.price = currentLowestSeller.price * 0.5;
and after this listings array looks like this:
[ { name: 'bob', price: 5 }, { name: 'jack', price: '12' } ]
How do I prevent this?
If you wanna recreate this just run this code:
var listings = [];
var name1 = 'bob';
var name2 = 'jack';
var price1 = '10';
var price2 = '12';
listings.push({
name: name1,
price: price1
})
listings.push({
name: name2,
price: price2
})
var currentLowestSeller = listings[0];
currentLowestSeller.price = currentLowestSeller.price * 0.5;
console.log(listings);
What I have tried:
I tried creating a copy of listings
array before doing anything.
var unchangedListings = listings;
var currentLowestSeller = listings[0];
currentLowestSeller.price = currentLowestSeller.price * 0.5;
console.log(unchangedListings);
But it didn't work.
Later I decided that const unchangedListings = listings;
would help. But for some reason it also changes a value defined as a constant.