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

173
Vistas
Confused about pushing array into array, JavaScript

My code looks like this

var res = [];
var temp = [];

function Permutations(target, size) {
  if (size === 0) {
    res.push(temp);
    console.log(res);
    return;
  }

  for (let i = 0; i < target.length; i++) {
    if (target[i] !== null) {
      temp.push(target[i]);
      target[i] = null;

      Permutations(target, size - 1);

      target[i] = temp.pop();
    }
  }
}

Permutations([1, 2, 3], 2);
console.log(res);

When I run my code, I can see my res stores each permutation as it is is being executed. However, when I log it outside the function, all the stored value disappeared.

[ [ 1, 2 ] ]
[ [ 1, 3 ], [ 1, 3 ] ]
[ [ 2, 1 ], [ 2, 1 ], [ 2, 1 ] ]
[ [ 2, 3 ], [ 2, 3 ], [ 2, 3 ], [ 2, 3 ] ]
[ [ 3, 1 ], [ 3, 1 ], [ 3, 1 ], [ 3, 1 ], [ 3, 1 ] ]
[ [ 3, 2 ], [ 3, 2 ], [ 3, 2 ], [ 3, 2 ], [ 3, 2 ], [ 3, 2 ] ]
[ [], [], [], [], [], [] ]   // This is my console.log outside the function
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The array temp holds is the same array throughout the complete execution of your code. And res.push(temp); adds this same array (not a copy of it) to your res array.

Here a related question about how Objects are handled in JavaScript: Is JavaScript a pass-by-reference or pass-by-value language?

So your code results in res having N times the same array.

You could copy the element stored in temp to a new array using [...temp], and push that to your res array.

var res = [];
var temp = [];

function Permutations(target, size) {
  if (size === 0) {
    res.push([...temp]);
    return;
  }

  for (let i = 0; i < target.length; i++) {
    if (target[i] !== null) {
      temp.push(target[i]);
      target[i] = null;

      Permutations(target, size - 1);

      target[i] = temp.pop();
    }
  }
}

Permutations([1, 2, 3], 2);
console.log(res);

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