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

158
Visualizações
JavaScript array looping over getting an error if array has mulitple data types

'''

const temperatures = ['error',3, -2, -6, -1, 'error', 9, 13, 17, 15, 14, 9, 5];

const calcTempAmplitide = function (temp) {
  let maxTemp = temp[0];
  let minTemp = temp[0];

  for (let i = 0; i < temp.length; i++) {
    const current_temp = temp[i];
    if (typeof current_temp !== 'number') continue;

    if (current_temp > maxTemp) maxTemp = current_temp;
    if (current_temp < minTemp) minTemp = current_temp;
  }

  return maxTemp - minTemp;
};
const amplitude = calcTempAmplitide(temperatures);

console.log(amplitude);

'''

After running this in Visual code I am getting a NaN value if I remove 'error' from the beginning then the code works Any solution for this

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

0

let maxTemp = temp[0];
let minTemp = temp[0];

means that if the array doesn't start with a number, comparisons won't make sense (and subtraction at the end won't work either).

How about filtering the array to remove non-numbers first?

const temperatures = ['error',3, -2, -6, -1, 'error', 9, 13, 17, 15, 14, 9, 5];

const calcTempAmplitide = function (temp) {
  const nums = temp.filter(val => typeof val === 'number');
  let maxTemp = nums[0];
  let minTemp = nums[0];

  for (let i = 0; i < nums.length; i++) {
    const current_temp = nums[i];
    if (current_temp > maxTemp) maxTemp = current_temp;
    if (current_temp < minTemp) minTemp = current_temp;
  }

  return maxTemp - minTemp;
};
const amplitude = calcTempAmplitide(temperatures);

console.log(amplitude);

or

const temperatures = ['error',3, -2, -6, -1, 'error', 9, 13, 17, 15, 14, 9, 5];

const calcTempAmplitide = function (temp) {
  const nums = temp.filter(val => typeof val === 'number');
  return Math.max(...nums) - Math.min(...nums);
};
const amplitude = calcTempAmplitide(temperatures);

console.log(amplitude);

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