Problem with splice

Problem with splice
0.0 0

function permAlone(str) {
  var combos = [];
  var num = 0;
  var options;
  str = str.split("");
    options = str;
  return num;

For some reason options doesn’t change back to str after each iteration. What am I missing?


That is because the following line assigns a reference to an array.

str = str.split("");

When the above code executes with the call permAlone(‘aab’), str gets assigned a reference (not the actual array) to [‘a’, ‘a’, ‘b’]. Inside your for loop, when you write options = str, you are just assigning the same reference to [‘a’, ‘a’, ‘b’] to options. Then when you write options.splice(i,1), the splice mutates the array referenced by options (which is the same array referenced by str). If you want to create a shallow copy of the str array inside the for loop, you would need to use slice as follows:

options = str.slice(); // creates a reference to a new array that looks the same as str


You’re not assigning it to str.