Home > front end >  Modify copied array without modifying the original array js
Modify copied array without modifying the original array js

Time:11-18

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)

CodePudding user response:

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

  • Related