This is a code I am writing for leetcode question 46. I implemented the same logic in Python and it worked, but when I tried to write a JS equivalent of it, it doesn't work as expected. The for loops are not running for some reason.
/**
* @param {number[]} nums
* @return {number[][]}
*/
const permute = nums => {
const final_list = [];
const bfs = (num, new_nums, current_list) => {
current_list.push(num);
if(new_nums.length === 0){
final_list.push(current_list);
return;
}
// This loop does not run for all iterations
for(i=0;i<new_nums.length;i++){
let new_nums2 = new_nums.filter(n => n!== new_nums[i]);
bfs(new_nums[i], [...new_nums2], [...current_list]);
}
}
// Only the runs for i=0
for(i=0;i<nums.length;i++){
let new_nums = nums.filter(n => n!== nums[i]);
bfs(nums[i], new_nums, []);
}
return final_list
};
Input: [1,2,3] Output: [[1,2,3]]
I know the problem is with the loops because I console logged the loops and it does not fully run. In the bottom loop for example, it only ran for i=0. What am I doing wrong here?
Edit: Thanks to @Bergi I found out what's wrong, I missed the declaration for I. I don't think the flagged duplicate question is very helpful here though, just by looking at the so-called duplicate question I would never have known where I went wrong.