I have the following function:
const biggestNumOfArray = (array) => {
if (Array.isArray(array)) {
let biggest = array[0];
for (i=0; i < array.length; i++) {
if (array[i] > biggest) {
biggest = array[i];
}
}
return biggest;
} else {
return NaN;
}
}
It's purpose is to output the biggest number in an array, ignoring non-number values, and return NaN if it isn't an array.
However, consider the following array:
let myArray = [undefined, 8, 74, -22, 269.64, 92];
All of a sudden, it outputs not 269.64
, but undefined
.
See, if the first element in an array is undefined
or NaN
, the variable biggest
gets stuck on it, as number > NaN
and number > undefined
on line 5 will always be false, which means the line to change the biggest
to the current will never be executed. How do I avoid that?
Note that this doesn't happen with undefined
s that aren't first, as number > undefined
also outputs false, unallowing to change the biggest
to it.
I tried to change the check for the number being the current biggest, by changing it to array[i] > biggest && array[i] != null
, using abstract equality to check for it being undefined
or null
, but it didn't work - I still got back undefined
. It also wouldn't cover NaN
.