Math.min.apply returns 0 for null

I would like to get the minimum value from an array. If the data contains a value null, Math.min.applyreturns 0for the value null. See this JSFiddle example . How can I get the true minimum value even if a value of zero exists in the array?

Code (same as in JSFiddle example):

var arrayObject= [ {"x": 1, "y": 5}, {"x": 2, "y": 2}, {"x": 3, "y": 9}, {"x": 4, "y": null}, {"x": 5, "y": 12} ];

var max = Math.max.apply(Math, arrayObject.map(function(o){return o.y;}));
var min = Math.min.apply(Math, arrayObject.map(function(o){return o.y;}));

$("#max").text(max);
$("#min").text(min);
+5
source share
5 answers

Well, the numerical value for nullis equal 0. If you do not want the values ​​to be nulltaken into account, you need to filter them:

var values = arrayObject.map(function(o){
    return o.y;
}).filter(function(val) {
    return val !== null
});

Link :Array#filter

+9
source

: null + - .

var max = Math.max.apply(Math, arrayObject.map(function(o) {
    return o.y == null ? -Infinity : o.y;
}));
var min = Math.min.apply(Math, arrayObject.map(function(o) {
    return o.y == null ? Infinity : o.y;
}));
+6

, , , null Math.min/max ( ), reduce , :

var arrayObject= [ {"x": 1, "y": 5}, {"x": 2, "y": 2}, {"x": 3, "y": 9}, {"x": 4, "y": null}, {"x": 5, "y": 12} ];
var min = var arrayObject.reduce(function(m, o) {
    return (o.y != null && o.y < m) ? o.y : m;
}, Infinity);
var max = var arrayObject.reduce(function(m, o) {
    return (o.y != null && o.y > m) ? o.y : m;
}, -Infinity);
+4
var validArray = $.grep( arrayObject, function(item, _){
                    return item.y != null;
               });
//That gives a new array without null values for "y"

..

var min = Math.min.apply(Math, validArray.map(function(o){return o.y;}));
0

() min

( ? " , ": " ")

!

0

All Articles