Get the Min/Max Values in an Object in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get the Min/Max Values in an Object #

To get the min and max values in an Object:

  1. Use the Object.values method to get an array of the object's values.
  2. Using spread syntax, pass the array to the Math.min() and Math.max() methods.
  3. The Math.min and Math.max methods return the lowest and highest of the passed in numbers.
index.js
const obj = {num1: 10, num2: 20, num3: 5, num4: 15}; const values = Object.values(obj); console.log(values); // 👉️ [10, 20, 5, 15] const max = Math.max(...values); console.log(max); // 👉️ 20 const min = Math.min(...values); console.log(min); // 👉️ 5

We used the Object.values method to get an array containing all the object's values.

We can't pass the array directly to the Math.max and Math.min methods because they expect multiple, comma-separated numbers and not an array of numbers.

index.js
const min = Math.min(10, 20, 5, 15); console.log(min); // 👉️ 5 const max = Math.max(10, 20, 5, 15); console.log(max); // 👉️ 20

To get around this, we used the spread operator to unpack the values of the array in the call to the min and max methods.

Alternatively, you can use the Object.keys() and the Function.apply() methods.

To get the min and max values in an Object:

  1. Use the Object.keys method to get an array of the object's keys.
  2. Map over the keys to get an array of the object's values.
  3. Use the apply method on both Math.min and Math.max, passing it null and the array of values as arguments.
index.js
const obj = {num1: 10, num2: 20, num3: 5, num4: 15}; const keys = Object.keys(obj); console.log(keys); // 👉️ ['num1', 'num2', 'num3', 'num4'] const values = keys.map(key => { return obj[key]; }); console.log(values); // 👉️ [10, 20, 5, 15] const max = Math.max.apply(null, values); console.log(max); // 👉️ 20 const min = Math.min.apply(null, values); console.log(min); // 👉️ 5

We used the Object.keys method to get an array of the object's keys.

We then used the Array.map method to iterate over the keys and to get an array of all the values of the object.

We passed the following arguments to the Function.apply method:

  1. the this argument - it's irrelevant for our use case
  2. the array of numbers, which will get passed as arguments to the Math.max and Math.min methods
We use the apply method to unpack the array into comma separated arguments when calling the Math.min and Math.max methods.

This is definitely the longer, more indirect and less elegant solution and should only be used if you have to support very old browsers.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.