I would like to get minimum value from an array. If the data contains null
value, Math.min.apply
returns 0
for null
value. Please see this JSFiddle example. How can I get true minimum value even if null value exists in 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);
The static function Math. min() returns the lowest-valued number passed into it, or NaN if any parameter isn't a number and can't be converted into one.
In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. The compiler assigns null to any uninitialized static and instance members of reference type. In the absence of a constructor, the getArticles() and getName() methods will return a null reference.
The Math. min() function returns the smallest of zero or more numbers. The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables.
max() starts with a search value of -Infinity , because any other number is going to be greater than -Infinity. Similarly, Math. min() starts with the search value of Infinity : “If no arguments are given, the result is Infinity .
These are what I've been using in 2020. Slightly shorter code.
const min = (values) => values.reduce((m, v) => (v != null && v < m ? v : m), Infinity);
const max = (values) => values.reduce((m, v) => (v != null && v > m ? v : m), -Infinity);
const arrayObject = [
{ x: 1, y: 5 },
{ x: 2, y: 2 },
{ x: 3, y: 9 },
{ x: 4, y: undefined },
{ x: 5, y: 12 },
];
const yValues = arrayObject.map((item) => item.y)
console.log(yValues)
console.log('min', min(yValues))
console.log('max', max(yValues))
Well, the numerical value for null
is 0
. If you don't want null
values to be be considered, you have to filter them out:
var values = arrayObject.map(function(o){
return o.y;
}).filter(function(val) {
return val !== null
});
Reference: Array#filter
Alternative to Felix's solution: treat null
as +
or -
infinity for min and max calls, respectively.
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;
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With