Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript function returning multiple outputs for same for loop iteration

(I am new to coding and trying to learn, this is my first question here. I hope I am clear enough)
I am trying to make a function that takes in an array of numbers and returns a string depending on how many elements in the array

for example const temps1 = [17, 21, 23];

and to return '...17°C in 1 days ...21°C in 2 days ...23°C 3 days' and so on

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this is the code I have written:

const temps1 = [17, 21, 23];

const temps2 = [12, 5, -5, 0, 4];

const printForecast = function (temps) {
  let displayer = [];

  for (let i = 0; i < temps.length; i++) {
    displayer.push(`...${temps[i]}°C in ${i + 1} days`);

    console.log(displayer.join(' '));

    // const displayer = [`...${temps[i]}°C in ${i + 1} days`];
  }
};

This is the output:

...17°C in 1 days

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

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

-

...12°C in 1 days

...12°C in 1 days ...5°C in 2 days

...12°C in 1 days ...5°C in 2 days ...-5°C in 3 days

...12°C in 1 days ...5°C in 2 days ...-5°C in 3 days ...0°C in 4 days

...12°C in 1 days ...5°C in 2 days ...-5°C in 3 days ...0°C in 4 days ...4°C in 5 days

(index):55 Live reload enabled.

>Solution :

You’re calling console.log inside the loop. This is causing the output to be printed for each iteration, resulting in the repeated lines. You should move the console.log statement outside the loop, so it only prints the final result.

Try this:

const temps1 = [17, 21, 23];
const temps2 = [12, 5, -5, 0, 4];

const printForecast = function (temps) {
  let displayer = [];

  for (let i = 0; i < temps.length; i++) {
    displayer.push(`...${temps[i]}°C in ${i + 1} days`);
  }

  // Moved the console.log statement outside the loop
  console.log(displayer.join(' '));
};

// Call the function with temps1 and temps2
printForecast(temps1);
printForecast(temps2);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading