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