Hello! Can anyone tell me why the push method is only saving the last item in the newArr
array?
My goal is to extract an array with the permutation of the passed values and in console.log()
it comes out right, but when I try to throw the results in an array through the push()
method, I leave it like this in the output.
function permAlone(str) {
var newArr = [];
function generate(n,arr){
var c = [];
var i = 0; //i while
for(var i = 0; i < n; i++){
c[i] = 0;
}
console.log(arr);
newArr.push(arr);
while(i < n){
if(c[i] < i){
if(i%2==0){
var aux = arr[0];
arr[0] = arr[i];
arr[i] = aux;
}
else{
var aux = arr[c[i]];
arr[c[i]] = arr[i];
arr[i] = aux;
}
console.log(arr)
newArr.push(arr);
c[i]+=1;
i = 0;
}
else{
c[i] = 0;
i++;
}
}
}
generate(str.length, str.split(''));
console.log('newArr');
console.log(newArr)
}
permAlone('aab');
Output:
[ 'a', 'a', 'b' ]
[ 'a', 'a', 'b' ]
[ 'b', 'a', 'a' ]
[ 'a', 'b', 'a' ]
[ 'a', 'b', 'a' ]
[ 'b', 'a', 'a' ]
newArr
[ [ 'b', 'a', 'a' ],
[ 'b', 'a', 'a' ],
[ 'b', 'a', 'a' ],
[ 'b', 'a', 'a' ],
[ 'b', 'a', 'a' ],
[ 'b', 'a', 'a' ] ]
[Finished in 0.1s]