doubt Array.push() Javascript

Asked

Viewed 3,156 times

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 from console.log(). I don’t know what the correct term is between adding an array or concatenating, but I think it would be adding.

  • 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.

1 answer

3


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

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

newArr.push(arr);   

Utilize .concat():

newArr = newArr.concat(arr); 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.