Is there a proper way to find the max value of a sparse array with undefined values?
Thanks
var testArr=[undefined,undefined,undefined,3,4,5,6,7];
console.log('max value with undefined is ',(Math.max.apply(null,testArr)));
// max value with undefined is NaN
console.log('max with arr.max()',testArr.max());
// Error: testArr.max is not a function
testArr=[null,null,null,3,4,5,6,7];
console.log('max value with null is ',(Math.max.apply(null,testArr)));
// max value with null is 7
I'd prefer not to do forEach if there is a built-in method.
Math.maxattempts to convert its arguments to numbers. Sinceundefinedis converted toNaN(ecma-international.org/ecma-262/5.1/#sec-9.3) it will fail with those values. You'll have to iterate over the values. The closest thing to "built-in" isArray.reduce.nullis converted to 0 so you'll get the wrong answer if your array is filled withnulls and negative numbers.