Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda