Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
js problem with arrays add comma after last array item

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!