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

130
Views
Sorting copied variable change the value of original variable

I have a problems that driving me nuts.

I need 2 arrays One to handle and other to use as reference. one gives the number and de second search position in the array.

This is the sample of my code:

var var1 = [37, 82, 4, 67, 23, 15];
var var2 = [];
function avaliador(a){
    var2 = var1;
    var2.sort(function(a, b) { return a - b; });
    console.log(var1);
    console.log(var2);
    //... function continues
}

My objective is have:

    console.log(var1); // [37, 82, 4, 67, 23, 15];
    console.log(var2); // [4, 15, 23, 37, 67, 82];

And this is what i got:

    console.log(var1); // [4, 15, 23, 37, 67, 82];
    console.log(var2); // [4, 15, 23, 37, 67, 82];

I missing something in my logic?

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

0

var2 is a reference to var1; they are the same array.

You need to clone var1 when assigning to var2. This can be done with slice:

var1 = [37, 82, 4, 67, 23, 15];

function avaliador(a){
    var2 = var1.slice();
    var2.sort(function(a, b) { return a - b; });
    console.log(var1);
    console.log(var2);
    //... function continues
}

avaliador()

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!