(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
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);