Skip to content Skip to sidebar Skip to footer

How To Check Min And Max Values Simultaneously In JavaScript?

I'm not sure if I understand correctly: retrieving data is much slower than running a logical operation on that data. So, instead of: var maxX = Math.max.apply(Math, data.map(func

Solution 1:

You can use Array.reduce to calculate all four values in one go:

var data = [
    { date: '10.10.2000', xAxis: 20.9, yAxis: 120 }, 
    { date: '11.10.2000', xAxis: 35.1, yAxis: 121 }, 
    { date: '12.10.2000', xAxis: 21.2, yAxis: 109 },
    { date: '13.10.2000', xAxis: 28.4, yAxis: 119 }, 
    { date: '14.10.2000', xAxis: 24.4, yAxis: 121 }
];

var init = {
    xMin: data[0].xAxis,
    xMax: data[0].xAxis,
    yMin: data[0].yAxis,
    yMax: data[0].yAxis
};

var result = data.reduce(function(previtem, curritem) {
    if (previtem.xMin > curritem.xAxis) previtem.xMin = curritem.xAxis;
    if (previtem.xMax < curritem.xAxis) previtem.xMax = curritem.xAxis;
    if (previtem.yMin > curritem.yAxis) previtem.yMin = curritem.yAxis;
    if (previtem.yMax < curritem.yAxis) previtem.yMax = curritem.yAxis;
    return previtem;
}, init);

console.log(result);
// { xMin: 20.9, xMax: 35.1, yMin: 109, yMax: 121 }

Solution 2:

You would have to write a function that does this traversal yourself and returns an array or object with min/max instead of just a single value. To my knowledge, that function isn't stock implemented.

A function like this wouldn't be terrible to write. Look at the how it does it in the Min or max example, then copy it w/reuse of the existing min/max functions and save two values instead of one.


Solution 3:

You can just use Array's sort:

var data = [
 { date: '10.10.2000', xAxis: 20.9, yAxis: 120 },
 { date: '11.10.2000', xAxis: 35.1, yAxis: 121 },
 { date: '12.10.2000', xAxis: 21.2, yAxis: 109 },
 { date: '13.10.2000', xAxis: 28.4, yAxis: 119 },
 { date: '14.10.2000', xAxis: 24.4, yAxis: 121 }
];

var maxY = data.sort(function(a,b){ return b.yAxis - a.yAxis; })[0].yAxis;
var maxX = data.sort(function(a,b){ return b.xAxis - a.xAxis; })[0].xAxis;

var minY = data.sort(function(a,b){ return a.yAxis - b.yAxis; })[0].yAxis;
var minX = data.sort(function(a,b){ return a.xAxis - b.xAxis; })[0].xAxis;

console.log("maxY:",maxY,"maxX:",maxX,"minY:",minY,"minX",minX);

Post a Comment for "How To Check Min And Max Values Simultaneously In JavaScript?"