0

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?

  • var1 and var2 are both referencing the same array. You need to create a copy of the array – Bart Dec 29 '21 at 19:28

1 Answers1

-1

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()
Spectric
  • 30,714
  • 6
  • 20
  • 43
  • 1
    So a = b o just reference? Always think when a use "=" i create a copy the variable/array and not just a reference. I learn all by myself so i didnt know it Thanks for help, it worked. I will try reformulate all my logic :) – Wallnut_Cracker Dec 29 '21 at 19:40