Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

233
Views
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)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!