Move arrays using "push" and "pop"

Asked

Viewed 1,834 times

2

Declare a function called "move", which takes two arrays, removes the last element of the first and adds it to the second.

Example:

var umArray = [1, 2, 3];
var outroArray = [4, 5];

mover(umArray, outroArray);

umArray //deveria ser [1, 2]
outroArray //deveria ser [4, 5, 3]

I did the following:

function mover (umArray,outroArray){
var umArray= [1, 2, 3]
var outroArray=[4, 5]
var pegarElemento = umArray.pop(); 
   outroArray.push( pegarElemento );
}

I don’t know how to proceed.

  • 1

    The same question was asked yesterday... https://answall.com/questions/423599/trocando-elements-nos-arrays-com-uma-functionHow-to

1 answer

1

Hello is simple the solution see:

function mover (umArray, outroArray){   
   var pegarElemento = umArray.pop(); 
   outroArray.push(pegarElemento);   
   console.log("primeiro Array", umArray);
   console.log("segundo Array", outroArray);
}
<!-- Declarar uma função chamada “mover”, que recebe dois arrays, remove o último elemento do primeiro e adiciona-o ao segundo. -->

<div>
Valor inicial do array 1:
[1, 2, 3]
</div>

<div>
Valor inicial do array 2:
[1, 2]
</div>

<br />
<button onclick="mover([1, 2, 3], [1, 2])" type="button">mover</button>

We call the function by passing the two arrays:

mover([1, 2, 3], [1, 2]);

Then we can take the last element of the first array:

var pegarElemento = umArray.pop(); 

And then add to the end of the second array

outroArray.push(pegarElemento);

and we finally use the console to display the result of the array:

console.log(outroArray);

Browser other questions tagged

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