skip to Main Content

I’m trying to print out the result from a loop onto the console but it keeps printing on a new line instead of printing everything on the same line.

This is the output I’m expecting:

...17°C in 1 days ... 21°C in 2 days ... 21°C in 3 days

But this is the output I keep getting:

... 17°C in 1 days

... 21°C in 2 days

... 23°C in 3 days

I’ve tried most of the answers I found but they are not working.

const arr =[17, 21, 23];

function printForcast(arr) {  
  for (let i = 0; i < arr.length; i++) {
    let days = i;

    if(i <= days){
      days +=1;
    }

    console.log(`... ${arr[i]}°C in ${days} days`); 
  }
  return arr;
}

printForcast(arr);
<!DOCTYPE html>

3

Answers


  1. Just collect the log items in an array and print at once in the end:

    const arr =[17, 21, 23];
    const log = [];
    function printForcast(arr) {
      
      //let currentTemp = temperatures[0];
      for (let i = 0; i < arr.length; i++) {
        let days = i;
    
       if(i <= days){
        days +=1;
        // console.log (days);
       }
        log.push(`... ${arr[i]}°C in ${days} days`); 
     }
      console.log(log.join(', '));
      return arr;
    }
    
    printForcast(arr);
    <!DOCTYPE html>
    Login or Signup to reply.
  2. Since console.log() will always output a newline, you’ll need to append (+=) your output to a string, and then log that after the loop:

    const arr =[17, 21, 23];
    
    function printForcast(arr) {
      
      let output = '';
      
      for (let i = 0; i < arr.length; i++) {
        let days = i;
    
       if(i <= days){
          days +=1;
       }
       output += `... ${arr[i]}°C in ${days} days`; 
     }
     
      console.log(output);
    }
    
    printForcast(arr);
    Login or Signup to reply.
  3. I think this simple snippet would work

    const arr = [17, 21, 23];
    function printForcast(arr) {
          let message = '';
          arr.forEach((item,index) => {
            const current = `... ${item}°C in ${index + 1} days `;
            message +=  current;
          });
          console.log(message.trimEnd()); 
          // trimEnd to avoid space on the last one 
    }
    printForcast(arr);

    Hope this helps 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search