﻿ JavaScript - How to find the Minimum value of an array object

# JavaScript - How to find the Minimum value of an array object

Let us assume, I have an array of objects (see below). Except one, two other attributes "price" and "change" has numeric value and I want to get the minimum value (ONLY) from of the object attributes (the lowest value). There are two ways I can do this.

The array object looks like this.

```const oStock = [
{ 'company': 'Google', 'price': 1296.25, 'change': +2.1 },
{ 'company': 'Cisco', 'price': 47.29, 'change': -0.29 },
{ 'company': 'SBI', 'price': 399.12, 'change': +5.85 }
];```

I just want the lowest or the minimum value, not the whole object.

There are two ways I can find the value.

1st, using Math.min() method, since its a number value.

2nd, using .reduce() method.

## 1st Method: Find minimum value from array objects using Math.min()

```<script>
const oStock = [
{ 'company': 'Google', 'price': 1296.25, 'change': +2.1 },
{ 'company': 'Cisco', 'price': 47.29, 'change': -0.29 },
{ 'company': 'SBI', 'price': 399.12, 'change': +5.85 }
];

document.write (Math.min(...oStock.map(item => item.change)));        // Output: -0.29
</script>```

Let me explain the method chain.

You can break above one-liner into two to beter understand how we got the result.

The .map() method gets all the value of the 'change' attribute
The result: 2.1,-0.29,5.85

The .min() method of the "Math" object returns the minimum value.
-0.29

Similarly, You can use the .max() method to find the maximum value.

## 2nd Method: Find minimum value from array objects using .reduce() method

I have explained about array.reduce() method in detail in my previous tutorial.

```<script>
const oStock = [
{ 'company': 'Google', 'price': 1296.25, 'change': +2.1 },
{ 'company': 'Cisco', 'price': 47.29, 'change': -0.29 },
{ 'company': 'SBI', 'price': 399.12, 'change': +5.85 }
];

const min = oStock.reduce((prev, curr) => {
return curr.change < prev.change ? curr : prev;
});

document.write (min.change);
</script>```

Similarly, you can find the maximum or the highest value by just using ">" (greater than) sign.

The .reduce() method can be used in many ways in JavaScript. See this example.

Happy coding.