1
function checkCashRegister(price, cash, cid) {
  let payBackAmount = cash - price;
  let tempArr = cid.slice();

  for (let i = 0; i < tempArr.length; i++) {
    tempArr[i][1] = 0;
  }
  console.log("cid is", cid);
}
checkCashRegister(19.5, 20, [
  ["PENNY", 1.01],
  ["NICKEL", 2.05],
  ["DIME", 3.1],
  ["QUARTER", 4.25],

  ["ONE", 90],
  ["FIVE", 55],
  ["TEN", 20],
  ["TWENTY", 60],
  ["ONE HUNDRED", 100],
]);

Here I am trying to copy an array from the parameterized function. cid is the array which I am trying to pass inside the function and I am trying to copy it into tempArr. Later when modifying the values of tempArr , the values of cid is changing as well. I have also tried copying the values using let tempArr=[...cid] and let tempArr=cid.slice(0)

2
  • 2
    You made a shalow copy, not a deep one. cid (great naming by the way :D) is a 2d array. If you add or remove elements from tempArr, the changes won't occur on cid, however, the elements of the array are still references, since they are arrays too. A quick and dirty way to do that is const tempArr = JSON.parse(JSON.stringify(cid)); Commented Nov 17, 2021 at 10:37
  • @Cid Thanks a lot for your explanation and the link. I really thought copying would be same since I was just trying to copy the contents of an array. Commented Nov 17, 2021 at 10:47

1 Answer 1

3

Here in the above code when you are copying one array to an other array the slice method and spread operator from javascript does a shallow copy, for your usecase you might want to do a deep clone of the object you can do let tempArr = JSON.parse(JSON.stringify(cid)) , instead of this you can also use deepClone from Lodash to deep clone a object

also please look at this thread What is the difference between a deep copy and a shallow copy? to know more about shallow clone and deep clone

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.