Write the 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.
Note! The automatic test takes care of assigning values to the arrays.
code below
var array1 =["first", "second", "kukka", "kakka"]
var array2 =["fourth", "fift", "rukka", "nukka", "sukka"]
function popandshift(){
console.log("First array: " + array1)
console.log("Second array: " + array2)
let i = 0;
uusi = array2.length;
while (i < uusi) {
i++;
const lastNumber = array2.pop()
array1.push(lastNumber)
const otherNumber = array2.shift()
array1.push(otherNumber)
if (array2.length === 0){
break}
}
console.log("Resulting array: " + array1);
}
popandshift()
for some reason. This works as intended but my program adds comma (,) after the last item on array why is it?
You're watching the result of pushing null to array1
let arr = ['a','b']
arr.push(null)
console.log("comma at the end:"+arr," length of the array",arr.length);
That's the result of using one counter to extract two values from the array plus having an array with an odd number of items. Your code slightly reworked:
var array1 =["first", "second", "kukka", "kakka"]
var array2 =["fourth", "fift", "rukka", "nukka", "sukka"]
function popandshift(){
console.log("First array: " + array1)
console.log("Second array: " + array2)
let i = 0;
uusi = array2.length;
while (i < uusi) {
i++;
const lastNumber = (i%2==0)?array2.shift():array2.pop()
array1.push(lastNumber)
if (array2.length === 0){
break}
}
console.log("Resulting array: " + array1);
}
popandshift()
Though you might want to refactor it a little bit (declaring of const out of the loop, thinking in another way to exit the loop). The way it is works, nevertheless.