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

130
Visualizações
Array remains empty but data is being pushed by creating a temp array

I am writing a program to generate subsets of a given array in Javascript. I am pushing the subsets into another global variable array called subMegaSet. But when I access subMegaSet in another function, the array contains empty subsets. But if I push values by creating another temp array, the subsets are being pushed into subMegaSet. I am not able to debug this.

function createSubsets(nums, n, arr, index){
if(arr.length >= 0){
    let temp = [];
    for(let item of arr){
        temp.push(item);
    }
    // subMegaSet.push(arr) ----> Empty array pushed 
    subMegaSet.push(temp);
}

if(index === n){
    return;
}

for(let i=index; i<n; i++){
    arr.push(nums[i]);
    createSubsets(nums, n, arr, i+1);
    arr.pop();
}

}

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There is only one arr array. Values get pushed to and popped from it, but it remains one, single array. This means that every time you do subMegaSet.push(arr) you add the same array to that subMegaSet. So it is not possible that subMegaSet[0] would be a different array than subMegaSet[1], ...etc. At all indexes you'll find the same array. If at the end of the whole procedure that array has become empty, then all you will find in subMegaSet will be an empty array -- repeatedly.

This is why you need to copy the array into a new (separate) array, when you push it unto subMegaSet, so that you guarantee that:

  • Any future push or pop on arr, does not affect the array that you just added to subMegaSet
  • All entries of subMegaSet are different array instances.

You can simplify that copying using spread syntax:

subMegaSet.push([...arr])
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