Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modify copied array without modifying the original array js

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading