1
Hello! Could anyone tell me why the push method is only saving the last item in the array newArr
?
My goal is to extract an array with the permutation of past and console.log()
it comes out right, but when I try to play the results in an array through the method push()
I left the way I show below, 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]
@Onosendai I want my
newArr
has the 6 arrays resulting fromconsole.log()
. I don’t know what the correct term is between adding an array or concatenating, but I think it would be adding.– dmg Geronimo
A array is an object. You are adding to
newArr
a new object, which happens to be a array. The end result is a array (newArr) that has an object in its internal collection.– OnoSendai