最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to skip NaN when using Math.min.apply? - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 7

Filter 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]));
发布评论

评论列表(0)

  1. 暂无评论