## Get The Minimum And Maximum Value Of A JavaScript Object

In this article, we will explore the process of obtaining the minimum and maximum values of a JavaScript object. To accomplish this task, we will retrieve an array of the object’s values using the Object.values() method and then utilize the min() and max() methods from the `Math` object by spreading the array using the … operator.

Contents

## Get The Minimum And Maximum Value Of A JavaScript Object

Let’s begin by creating an object and initializing it with numerical variables. For the sake of this scenario, we will be using numeric values.

``````const numbers = {

num1: 1,

num2: 2,

num3: 3,

num4: 4

};``````

To proceed, we need to obtain an array of the object’s values using the Object.values() method and store this array in a variable.

``const numberValues = Object.values(numbers);``

With the array of values in place, we can now utilize the max() and min() methods of the `Math` object. By passing in our array as an argument using the spread operator (…), we can acquire the maximum and minimum values.

Let’s save the results in two variables, maxValue and minValue, and print them to the console for verification.

``````const maxValue = Math.max(...numberValues);

const minValue = Math.min(...numberValues);

console.log(minValue, maxValue);``````

By executing the code, we can observe the minimum value as 1 and the maximum value as 4 within our object.

To make our logic reusable for any object, we can encapsulate it within a function. This function will accept an object as an argument, create an array of values from the object, obtain the minimum and maximum values, and store them in separate variables. Finally, it will return an object containing the minimum and maximum values.

Let’s define the getMinMaxValues function:

``````const getMinMaxValues = (object) => {

let objectValues = Object.values(object);

let minValue = Math.min(...objectValues);

let maxValue = Math.max(...objectValues);

return {

minimum: minValue,

maximum: maxValue

};

};

console.log(getMinMaxValues(numbers));``````

By calling getMinMaxValues(numbers), we can see the result of our function, which provides an object containing the minimum and maximum values of the `numbers` object.

## Conclusion

In conclusion, by utilizing JavaScript’s Object.values() method, along with the min() and max() methods from the `Math` object, we can easily obtain the minimum and maximum values of a JavaScript object. This approach allows us to perform numeric comparisons within objects and retrieve essential statistical information.