Home > Software engineering >  How to efficiently list an array as a string in order?
How to efficiently list an array as a string in order?

Time:09-24

This is my first question being asked on this site in my Dev journey!

I have an array - const dataOne = [17, 21, 23];

I need to list the values in this array in order to look like this when I log into the console:

"17°C in 1 day, 21°C in 2 days, 23°C in 3 days"

The code below logs exactly what I want, but I know this is not the most efficient way to go about it. is there a "cleaner" or better way to do this without hard-coding the array in the return statement? Ex: ${arr[i 1]}

Thank you!

const dataOne = [17, 21, 23];

const printForecast = function (arr) {
  for (let i = 0; i < arr.length; i  ) {
    return `${arr[i]}°C in ${i   1} day, ${arr[i   1]}°C in ${i   2} days, ${arr[i   2]}°C in ${i   3} days`;
  }
};

console.log(printForecast(dataOne));

CodePudding user response:

You can simply use map and join to achieve the desired result

This is the cleanest way to achieve. In this approach you don't have to track where you have to place comma(,). Just map over the array and then join them with , simple

const dataOne = [17, 21, 23];

const printForecast = function (arr) {
  return arr.map((t, i) => `${t}°C in ${i   1} day${i !== 0 ? "s" : ""}`)
            .join(", ");
};

console.log(printForecast(dataOne));

If you want to use reduce then you can do as:

const dataOne = [17, 21, 23, 25];

const printForecast = function (arr) {
  return dataOne.reduce((agg, x, index, src) => (agg  = `${x}°C in ${index   1} day${index !== 0 ? "s" : ""}${ index !== src.length - 1 ? ", " : ""}`),"");
};

console.log(printForecast(dataOne));

CodePudding user response:

Firstly, if the code works for you and you understand it, it is good enough. Try to optimize later when you are very well versed with the basics.

For the sake of this question, you can use .reduce() to solve the issue. It is used to iterate over the values to aggregate to and return a single computed result.

const dataOne = [17, 21, 23, 25];

const printForecast = function(arr) {
  let newString = dataOne.reduce((agg, x, index) => {
    if (index === 0) {
      agg = agg   x   '°C in '   (index   1)   ' day';
    } else {
      agg = agg   ', '   x   '°C in '   (index   1)   ' days';
    }
    return agg;
  }, '');
  return newString
}

console.log(printForecast(dataOne));

  • Related