Home > Back-end >  How can i make all three console.log into a single line?
How can i make all three console.log into a single line?

Time:09-22

// code

const arr1 = [17, 21, 34];
const printForecast = function (arr1) {
  for (var i = 0; i < arr1.length; i  ) {
    console.log(`${arr1[i]} C on day ${arr1.indexOf(arr1[i])   1}`);
  }
};

printForecast(arr1);

// I want an output like this--> 17 C on day 1 21 C on day 2 34 C on day 3

CodePudding user response:

  1. Your function should ideally be returning a value.

  2. Use map to iterate over the array, create a new array of strings, and join that up into a new string before you return it.

const arr1 = [17, 21, 34];

function getForecast(arr1) {
  return arr1.map((num, i) => {
    return `${num} C on day ${i   1}`;
  }).join(', ');
};

console.log(getForecast(arr1));

CodePudding user response:

Construct the string inside the loop. Assign it to a variable and then print it outside the for loop.

const arr1 = [17, 21, 34];

const printForecast = function(arr1) {
  let string = "";
  for (var i = 0; i < arr1.length; i  ) {
    string  = `${arr1[i]} C on day ${arr1.indexOf(arr1[i])   1}, `;
  }
  console.log(string);
};

printForecast(arr1);

CodePudding user response:

const arr1 = [17, 21, 34];

arr1.forEach((item, index) => {
  console.log(`${item} C on day ${index   1}`);
});

  • Related