Categories
JavaScript Answers

How to get the min/max values among properties of object?

Spread the love

Sometimes, we want to get the min/max values among properties of object.

In this article, we’ll look at how to get the min/max values among properties of object.

How to get the min/max values among properties of object?

To get the min/max values among properties of object, we can use the Object.values method to return array with the property values of an object.

Then we can use the Math.min and Math.max to get the min and max value from the array of values respectively.

For instance, we write:

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

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

console.log(min, max);

We call Object.values with obj to return an array of obj property values.

Then we call Math.min and Math.max with arr spread into them as arguments to compute the min and max values of arr respectively.

Therefore min is 0.35 and max is 5.

Conclusion

To get the min/max values among properties of object, we can use the Object.values method to return array with the property values of an object.

Then we can use the Math.min and Math.max to get the min and max value from the array of values respectively.

Leave a Reply

Your email address will not be published. Required fields are marked *