0

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.

5
  • forEach is a built-in method Commented Jan 20, 2015 at 21:55
  • possible duplicate of JavaScript: min & max Array values? Commented Jan 20, 2015 at 21:55
  • @DanielWeiner a built-in method of finding the max value Commented Jan 20, 2015 at 22:00
  • Math.max attempts to convert its arguments to numbers. Since undefined is converted to NaN (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" is Array.reduce. Commented Jan 20, 2015 at 22:03
  • Also, null is converted to 0 so you'll get the wrong answer if your array is filled with nulls and negative numbers. Commented Jan 20, 2015 at 22:15

2 Answers 2

2
testArr.reduce(function(a,b){
  if (isNaN(a) || a === null || a === '') a = -Infinity;
  if (isNaN(b) || b === null || b === '') b = -Infinity;
  return Math.max(a,b)
}, -Infinity);
Sign up to request clarification or add additional context in comments.

2 Comments

Empty strings with negative numbers would be an issue as it stands.
Good catch, I just updated my solution to account for empty strings.
2

None of your examples are true sparse arrays (they don't have any 'holes'), but you could use Array.prototype.filter (ECMA5) to test the value isFinite. For better accuracy ECMA6 will offer Number.isFinite. Remember there are also limits to the number of arguments that Function.prototype.apply can handle (often 65536 arguments). Of course, isFinite may not be suitable for your application, if you want Infinity and -Infinity, then you should use a different test. An empty string with negative numbers would be an issue in this current exampe.

var testArr = [undefined, , , 3, 4, 5, 6, 7];

document.body.textContent = Math.max.apply(null, testArr.filter(function (x) {
    return isFinite(x);
}));

2 Comments

Simply testArr.filter(isFinite)
@georg Yes indeed, I was thinking that having it verbose may be better for the answer as it is not clear that isFinite is the best check for the question raised.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.