How do I get the lowest value and highest value of the array separately with javascript and jQuery?
var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
The lowest value in this case is 444.9 and the highest 984.9.
How do I get the lowest value and highest value of the array separately with javascript and jQuery?
var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
The lowest value in this case is 444.9 and the highest 984.9.
The simplest way would look like this:
var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
var min = Math.min(...arr);
var max = Math.max(...arr);
console.log(min); // 444.9
console.log(max); // 984.9
The most "conventional" way would be to combine .reduce()
with Math.max|Math.min
.
I also added a .map(Number)
because you have strings and it is better to work with numbers (even if it works without it).
The Math.max
and Math.min
accept two (or more) arguments, and return the major / minor. The .reduce()
passes the previous value and the new value, which fits perfectly.
To know the maximum using .reduce()
:
var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
var max = arr.map(Number).reduce(function(a, b) {
return Math.max(a, b);
});
console.log(max); // 984.9
To know the minimum using .reduce()
:
var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
var min = arr.map(Number).reduce(function(a, b) {
return Math.min(a, b);
});
console.log(min); // 444.9
I recommend using the Lodash library. The lib is extra small and has several other very useful features.
It would just be this code below:
var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
console.log(_.min(arr)); //444.9
console.log(_.max(arr)); //984.9
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
You'll have to convert the strings into numbers before you make the comparisons:
var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
var maior = Number.NEGATIVE_INFINITY,
menor = Infinity;
arr.forEach(function(item){
if (Number(item) > maior) maior = item;
if (Number(item) < menor) menor = item;
});
console.log(maior, menor)
You can use Math.Max () and the Math.Min () to get the values, such as it's something relatively simple I'll just point the links and let you study =]
This too