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

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:

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

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?

>Solution :

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()
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