Javascript: 2 Ways to Find Min/Max Property of an Object

Last updated on June 23, 2022 A Goodman Loading... Post a comment

This short and straight-to-the-point shows you two different ways to get the minimum and maximum properties of a Javascript object (assuming this object has two or more properties with all values being numeric).

The Modern Way

With modern Javascript (ES6 or later), you can use the Math.min() and Math.max() functions with the spread syntax (…) to get things done.

Example:

const obj = {
    'a': 10,
    'b': 20,
    'c': 5,
    'd': 15,
    'e': 25,
    'f': 30
}

// get the array of values
const arr = Object.values(obj);

// find the min value
const min = Math.min(...arr);
console.log('min value:', min)

// find the max value
const max = Math.max(...arr);
console.log('max value:', max);

Output:

min value: 5
max value: 30

The Traditional Approach

The class way to find the min and max values in an object is to loop through it.

Example:

var obj = {
    'a': 11,
    'b': 20,
    'c': 8,
    'd': 15,
    'e': 25,
    'f': 19
}

var keys = Object.keys(obj);

// Give min and max initial values
var min = obj[keys[0]];
var max = obj[keys[0]];

// loop through the object
for (i = 1; i < keys.length; i++) {
    // find the min 
    if(min > obj[keys[i]]) {
        min = obj[keys[i]];
    }

    // find the max
    if(max < obj[keys[i]]) {
        max = obj[keys[i]];
    }
}

console.log('min value:', min);
console.log('max value:', max);

Output:

min value: 8
max value: 25

Further reading:

You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like