15

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);
4
  • 3
    There is no JSON in your example... fixed. Commented Aug 5, 2012 at 16:00
  • The Math.min function performs (the internal function) ToNumber() on each array element, which in turn coerces the values to Number. Coercion sucks, we knew that. :P Commented Aug 5, 2012 at 16:07
  • 1
    @ŠimeVidas simply leaving the property out would make it undefined, which in turn turns to NaN which is easily filtered out with .filter(isFinite)
    – Esailija
    Commented Aug 5, 2012 at 16:16
  • @Esailija Yes, that would be a great solution. Commented Aug 5, 2012 at 16:30

9 Answers 9

13

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

4
  • 2
    Or map null to Infinity. Would save some bytes and additional n function calls.
    – Prinzhorn
    Commented Aug 5, 2012 at 16:03
  • @Prinzhorn: Yeah, that would work too... just that you have to map them again for max to -Infinity. Depends on what you are going to do with the data. Commented Aug 5, 2012 at 16:05
  • Is this right? I am still getting 0, look here at forked version:jsfiddle.net/jeryslo/nfSUm Commented Aug 5, 2012 at 16:11
  • @Jernej: You only used the filtered values for max, not for min. Commented Aug 5, 2012 at 16:12
8

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;
}));
2
  • Vow. I've never seen infinity been put to use. I'd upvote this twice if I could. :) Commented Aug 5, 2012 at 16:11
  • 1
    Is there a reason to use the constant on Number, wouldn't the literal Infinity (and -Infinity) be easier?
    – Bergi
    Commented Aug 5, 2012 at 17:38
4

I think instead of mapping properties, filtering out null values, and applying Math.min/max (as suggested by the other answers) the reduce function will save you some time and code, by directly applying the logic:

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);
3
  • Interesting solution. What is the performance gain in terms of O notation? Commented Aug 5, 2012 at 16:16
  • O(n) not unlike any other solution.
    – Esailija
    Commented Aug 5, 2012 at 16:17
  • Landau notation? None. But you save some function calls and some memory by not creating the intermediate arrays
    – Bergi
    Commented Aug 5, 2012 at 16:24
1

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))

0
var validArray = $.grep( arrayObject, function(item, _){
                    return item.y != null;
               });
//That gives a new array without null values for "y"

Now do..

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

Use lodash:

_.min([5, null]) = 5
0

This one seems the cleanest and worked best for me:

const applicableValues = originalData.filter(o => Number.isInteger(o[propertyName])); // or o[propertyName]!== null

const minValue = Math.min(...applicableValues.map(o => o[propertyName]));
0
0
Math.min(...[...arrayObject.filter(n => n["y"] != null)].map(a=>a["y"])) 

pull out the null values, then create array of the y values, then grab the minimum from that array

-1

have you tried the conditional (ternary) operator in the min function

(if Value is Null ? "a large value so that does not fall min criteria " : "original value")

Hope this helps!

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.