doubt Array.push () Javascript

1

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]
    
asked by anonymous 02.02.2017 / 19:04

1 answer

3

You are adding an array ( arr ) as an object to the inner collection of newArr .

If you want to concatenate the elements of arr with the elements of newArr , instead of

newArr.push(arr);   

Use .concat() :

newArr = newArr.concat(arr); 
    
02.02.2017 / 19:15