Manuel
Manuel

Reputation: 18

execution of loop stops after recursive function call - javascript

I'm trying to make a function that makes an array of all the possible permutations without repetition of the chars in a given array. The problem is that when the recursive call of recur() is made, the rest of the for loop is not executed and as a result the var total consists of 1 string.

   function recur(arr,wordArr) {
    if(arr.length == 0) {
      total.push(wordArr);
    } else {
        for(var i = 0;i < arr.length;i++) {
          var temp = arr;
          var newwordArr = wordArr;
          newwordArr += temp.splice(i, 1);
          recur(temp,newwordArr);
        }
    }
  }



  var arr = "abc".split("");
  var total = [];
  recur(arr,'');
  console.log(total);

Calling recur([a,b],'') should make total = ['ab','ba']

There is something I'm not seeing or what I'm trying to do is simply not allowed. Couldn't find the answer to this even tought I did a lot of searching.

Upvotes: 0

Views: 708

Answers (1)

Gor
Gor

Reputation: 2908

You need to copy your array in each step of for loop

function recur(arr,wordArr) {
if(arr.length == 0) {
  total.push(wordArr);
} else {
    for(var i = 0;i < arr.length;i++) {
      var temp = Array.from(arr);
      var newwordArr = wordArr;
      newwordArr += temp.splice(i, 1);
      recur(temp,newwordArr);
    }
}
}

Because in JS, all objects are referances, and writing var temp = arr; it will not create new array, it just will create reference to old array arr.

Array.from(oldArray|oldSet)

this function will create new Array and fill with old.

Read more about

Upvotes: 1

Related Questions