Reputation: 33
I'm currently trying to push a variable into an array, and change the value of the variable without changing the value that has been pushed into an array. How do i do this? Here is the section that I'm currently trying to solve.
if (cid[j][1] <= toPay && cid[j][1] !== 0) {
change.push(cid[j]);
toPay = toPay - cid[j][1];
cid[j][1] = 0;
}
Here's the full code:
function checkCashRegister(price, cash, cid) {
let j = 0;
let change = [];
var currency = {
'ONE HUNDRED': 100,
TWENTY: 20,
TEN: 10,
FIVE: 5,
ONE: 1,
QUARTER: 0.25,
DIME: 0.1,
NICKEL: 0.05,
PENNY: 0.01
}
let toPay = cash - price;
let index = 0;
for (let j = cid.length - 1; j >= 0; j--) {
if (toPay == 0) {
break;
}
if (cid[j][1] <= toPay && cid[j][1] !== 0) {
change.push(cid[j]);
toPay = toPay - cid[j][1];
cid[j][1] = 0;
}
if (cid[j][1] > toPay) {
if (currency[cid[j][0]] < toPay) {
index = ~~(toPay / currency[cid[j][0]]);
toPay = (toPay - (index * currency[cid[j][0]])).toFixed(2);
cid[j][1] = (index * currency[cid[j][0]]);
change.push(cid[j]);
}
}
}
return change;
}
Upvotes: 1
Views: 2014
Reputation: 4736
You need to pass a copy of the array to your function.
Using the spread operator to copy an array is acceptable if your array only contains scalar values:
let array1 = [1, 2, 3, 4]
let array2 = […array1]
However, if your array contains objects or other arrays, you need to do a deep copy to ensure that your objects are all new and not referencing the original values:
let array2 = JSON.parse(JSON.stringify(array1))
Upvotes: 4
Reputation: 56
When you call the function change.push(cid[j]);
, only a pointer to the array cid[j]
is added to your change
array. If you then assign cid[j][1] = 0;
, the underlying object changes. What you need to do is clone the array when pushing it.
change.push([...cid[j]]);
This makes use of the spread syntax to essentially 'pull' the array apart and build a new (cloned) one out of it. Assuming your array consists only of numbers, you should be fine. Watch out if you clone arrays of objects, on which you can find more information here.
Upvotes: 0