I am having beginners trouble with a JS exercise.
I have to write a function popAndShift(). The function has to first print the the contents of the arrays array1 and array2. After this, the elements of array2 will be deleted, alternating between the .pop() and .shift() methods (starting with .pop()), while adding the removed values to the end of array1. Finally, the contents of array1 will be printed.
**The automatic test takes care of assigning values to the arrays.
**
My code passes for the first test but fails for the second. I was wondering if I have to use a for loop to achieve the desired result. Would appreciate some help on this, thank you.
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);
}
>Solution :
I looked at the image you provided, and this new function should work and give the expected output. we are storing a variable called usePop and then alternating 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