Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!