Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda