Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!