[javascript] Fast way to get the min/max values among properties of object

I have an object in javascript like this:

{ "a":4, "b":0.5 , "c":0.35, "d":5 }

Is there a fast way to get the minimum and maximum value among the properties without having to loop through them all? because the object I have is huge and I need to get the min/max value every two seconds. (The values of the object keeps changing).

This question is related to javascript jquery

The answer is


// 1. iterate through object values and get them
// 2. sort that array of values ascending or descending and take first, 
//    which is min or max accordingly
let obj = { 'a': 4, 'b': 0.5, 'c': 0.35, 'd': 5 }
let min = Object.values(obj).sort((prev, next) => prev - next)[0] // 0.35
let max = Object.values(obj).sort((prev, next) => next - prev)[0] // 5

var newObj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
var maxValue = Math.max(...Object.values(newObj))
var minValue = Math.min(...Object.values(newObj))

For nested structures of different depth, i.e. {node: {leaf: 4}, leaf: 1}, this will work (using lodash or underscore):

function getMaxValue(d){
    if(typeof d === "number") {
        return d;
    } else if(typeof d === "object") {
        return _.max(_.map(_.keys(d), function(key) {
            return getMaxValue(d[key]);
        }));
    } else {
        return false;
    }
}

Here's a solution that allows you to return the key as well and only does one loop. It sorts the Object's entries (by val) and then returns the first and last one.

Additionally, it returns the sorted Object which can replace the existing Object so that future sorts will be faster because it will already be semi-sorted = better than O(n). It's important to note that Objects retain their order in ES6.

_x000D_
_x000D_
const maxMinVal = (obj) => {_x000D_
  const sortedEntriesByVal = Object.entries(obj).sort(([, v1], [, v2]) => v1 - v2);_x000D_
_x000D_
  return {_x000D_
    min: sortedEntriesByVal[0],_x000D_
    max: sortedEntriesByVal[sortedEntriesByVal.length - 1],_x000D_
    sortedObjByVal: sortedEntriesByVal.reduce((r, [k, v]) => ({ ...r, [k]: v }), {}),_x000D_
  };_x000D_
};_x000D_
_x000D_
const obj = {_x000D_
  a: 4, b: 0.5, c: 0.35, d: 5_x000D_
};_x000D_
_x000D_
console.log(maxMinVal(obj));
_x000D_
_x000D_
_x000D_


You can also try with Object.values

_x000D_
_x000D_
const points = { Neel: 100, Veer: 89, Shubham: 78, Vikash: 67 };_x000D_
_x000D_
const vals = Object.values(points);_x000D_
const max = Math.max(...vals);_x000D_
const min = Math.min(...vals);_x000D_
console.log(max);_x000D_
console.log(min);
_x000D_
_x000D_
_x000D_


min and max have to loop through the input array anyway - how else would they find the biggest or smallest element?

So just a quick for..in loop will work just fine.

var min = Infinity, max = -Infinity, x;
for( x in input) {
    if( input[x] < min) min = input[x];
    if( input[x] > max) max = input[x];
}

You could try:

const obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
const max = Math.max.apply(null, Object.values(obj));
console.log(max) // 5

// Sorted
let Sorted = Object.entries({ "a":4, "b":0.5 , "c":0.35, "d":5 }).sort((prev, next) => prev[1] - next[1])
>> [ [ 'c', 0.35 ], [ 'b', 0.5 ], [ 'a', 4 ], [ 'd', 5 ] ]


//Min:
Sorted.shift()
>> [ 'c', 0.35 ]

// Max:
Sorted.pop()
>> [ 'd', 5 ]

This works for me:

var object = { a: 4, b: 0.5 , c: 0.35, d: 5 };
// Take all value from the object into list
var valueList = $.map(object,function(v){
     return v;
});
var max = valueList.reduce(function(a, b) { return Math.max(a, b); });
var min = valueList.reduce(function(a, b) { return Math.min(a, b); });

Using the lodash library you can write shorter

_({ "a":4, "b":0.5 , "c":0.35, "d":5 }).values().max();

Update: Modern version (ES6+)

_x000D_
_x000D_
let obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };

let arr = Object.values(obj);
let min = Math.min(...arr);
let max = Math.max(...arr);

console.log( `Min value: ${min}, max value: ${max}` );
_x000D_
_x000D_
_x000D_


Original Answer:

Try this:

let obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
var arr = Object.keys( obj ).map(function ( key ) { return obj[key]; });

and then:

var min = Math.min.apply( null, arr );
var max = Math.max.apply( null, arr );

Live demo: http://jsfiddle.net/7GCu7/1/