Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda