Math.min.apply returns 0 for null

Viewed 14303

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);
8 Answers

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

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

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!

Related