To get the smallest number in an array of numbers, I use this:
var smallestNumber = Math.min.apply(null, arrayOfNumbers.map(function(x) { return x; }));
but if one of the numbers is NaN, smallestNumber returns NaN. Same thing happens with the max operator. (I might have Infinity but I am not sure if it gets returned)
How do I skip all the NaN's and return the smallest number?
To get the smallest number in an array of numbers, I use this:
var smallestNumber = Math.min.apply(null, arrayOfNumbers.map(function(x) { return x; }));
but if one of the numbers is NaN, smallestNumber returns NaN. Same thing happens with the max operator. (I might have Infinity but I am not sure if it gets returned)
How do I skip all the NaN's and return the smallest number?
Share Improve this question asked Oct 9, 2013 at 18:29 Tony_HenrichTony_Henrich 44.3k80 gold badges253 silver badges390 bronze badges 4-
That
.map()
call returns a copy of the original array ... – Pointy Commented Oct 9, 2013 at 18:31 -
2
array.map(function(x) { return x; })
does approximately nothing. – poke Commented Oct 9, 2013 at 18:31 -
I usually prefer
Array.prototype.reduce
, as you could run into issues with the number of arguments if the array is too large. – zzzzBov Commented Oct 9, 2013 at 18:35 - Downvoters, care to explain your judgment? – poke Commented Oct 9, 2013 at 18:43
3 Answers
Reset to default 7Filter out the NaN
entries:
var smallest = Math.min.apply(null, arrayOfNumbers.filter(function(n) { return !isNaN(n); }));
Following zzzzBov’s idea, you could also do this using Array.reduce
. This would allow you to skip on intermediary array that would be created from the filter:
var minReduce = function (a, b) { return (isNaN(b) || b > a) ? a : b };
var smallest = arrayOfNumbers.reduce(minReduce, Number.MAX_VALUE);
(I only stored the function separately in a variable to make it more readable in the answer; you are free to use a an anonymous function within the reduce call itself.)
Based on the solution Pointy provided but i find this one more accurate:
const applicableValues = originalData.filter(o => number.isInteger(o[propertyName]));
const minValue = Math.min(...applicableValues.map(o => o[propertyName]));