There are many ways to get the min value in an array of objects in JavaScript. Some simple and basic methods are to loop through all elements and compare them to the lowest value or sort the array or Math. min.
The array looks like this:
var myArray = [ {"ID": 1, "Rate": 1200}, {"ID": 2, "Rate": 1000}, {"ID": 3, "Rate": 3000}, {"ID": 4, "Rate": 6000} ]
Examples of JavaScript find min value in an array of objects
HTML example code.
Example 1 : Loop
One way is to loop through all elements and compare them to the lowest value.
<!DOCTYPE html>
<html>
<head>
<script>
var myArray = [
{"ID": 1, "Rate": 1200},
{"ID": 2, "Rate": 1000},
{"ID": 3, "Rate": 3000},
{"ID": 4, "Rate": 6000}
]
var min = Number.POSITIVE_INFINITY;
var tmp;
for (var i=myArray.length-1; i>=0; i--) {
tmp = myArray[i].Rate;
if (tmp < min) min = tmp;
}
alert(min);
</script>
</head>
<body>
</body>
</html>
Output:
Example 2: Math.min.apply
<!DOCTYPE html>
<html>
<head>
<script>
var myArray = [
{"ID": 1, "Rate": 1200},
{"ID": 2, "Rate": 1000},
{"ID": 3, "Rate": 3000},
{"ID": 4, "Rate": 6000}
]
const minmax = (someArrayOfObjects, someKey) => {
const values = someArrayOfObjects.map( value => value[someKey] );
return {
min: Math.min.apply(null, values),
};
};
console.log(minmax(myArray, 'Rate'));
</script>
</head>
<body>
</body>
</html>
Output: Object { min: 1000 }
Example 3: sort()
First sort the JS array with a custom sorting function:
var sorted = persons.sort(function(a, b) {
if(a.Age > b.Age) return 1;
else if(a.Age < b.Age) return -1;
else return 0;
Then take the first-> Minimum and last -> Maximum:
var min = sorted[0],
max = sorted[sorted.length - 1];
Do comment if you have any doubts and suggestions on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version