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

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

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 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