I'm trying to write a function that would return all permutations of a given array of numbers, as in the examples below:
a = [1, 1, 2]
permutator(a) = [
  [1,1,2],
  [1,2,1],
  [2,1,1]
]
b = [2, 3, 4]
permutator(b) = [
  [2,3,4],
  [2,4,3],
  [3,2,4],
  [3,4,2],
  [4,2,3],
  [4,3,2]
]
order of the results isn't accurate
Can you explain why the code below doesn't work? I tried debugging and I think the variables temp and result aren't being kept in memory as arrays but I'm not sure if that is the case nor how to solve it.
permutator = (array) => {
  const result = [];
  array.forEach((num, i) => {
    array.forEach((num2, j) => {
      if (i !== j) {
        let temp = array;
        temp[i] = temp[j];
        temp[j] = num;
        console.log(`temp: ${temp}`);
        console.log(`result: ${result}`);
        if (!result.includes(temp)) result.push(temp);
        console.log(`result: ${result}`);
      }
    });
  });
  return result;
}
as you can see I tried console.logging everything to no avail...
 
    