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();
}
}
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:
push or pop on arr, does not affect the array that you just added to subMegaSetsubMegaSet are different array instances.You can simplify that copying using spread syntax:
subMegaSet.push([...arr])