Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

251
Visualizações
How to efficiently list an array as a string in order?

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]}

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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda