Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
To get the min and max values in an Object:
Object.values
method to get an array of the object's values.Math.min()
and Math.max()
methods.Math.min
and Math.max
methods return the lowest and highest of the
passed in numbers.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.
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:
Object.keys
method to get an array of the object's keys.apply
method on both Math.min
and Math.max
, passing it null
and the array of values as arguments.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:
this
argument - it's irrelevant for our use caseMath.max
and Math.min
methodsapply
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.