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