Create a function that alternates between .pop() and .shift()
P粉403804844
P粉403804844 2023-09-11 21:30:34
0
1
460

I'm having beginner's difficulty with my JS exercises. I need to write a function popAndShift(). This function first prints the contents of arrays array1 and array2. Then, alternately remove elements of array2 using the .pop() and .shift() methods (starting with .pop()) and add the removed values ​​to the end of array1. Finally, print the contents of array1. **Automated tests assign values ​​to arrays. ** My code passes the first test but fails the second one. I'm wondering if I need to use a for loop to achieve the desired result. thanks for your help.

Code and test screenshots

function popAndShift(){

console.log("First array: " + array1);
console.log("Second array: " + array2);

RemoveE =array2.pop();
RemoveB=array2.shift();
RemoveC =array1.push(RemoveE,RemoveB,array2);
    
console.log("Resulting array:" + array1);
}

P粉403804844
P粉403804844

reply all(1)
P粉920835423

I looked at the image you provided and this new function should work and produce the expected output. We are storing a variable called usePop and then alternately using it each time we run the loop until array2 is empty.

const array1 = ["A"];
const array2 = ["B", "C", "D", "E", "F", "G", "H", "I"];

function popAndShift(){
  console.log("First array: " + array1);
  console.log("Second array: " + array2);

  let usePop = true;
  while (array2.length > 0) {
    array1.push(usePop ? array2.pop() : array2.shift());
    usePop = !usePop;
  }

  console.log("Resulting array: " + array1);
}

popAndShift();

Output:

First array: A
Second array: B,C,D,E,F,G,H,I
Resulting array: A,I,B,H,C,G,D,F,E
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template