Take the lowest value and the highest value of an array with Javascript?

Asked

Viewed 11,999 times

1

How do I get the lowest value and the 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.

4 answers

7


The simplest way would be 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 the .reduce() with the Math.max|Math.min.

I also added a .map(Number) because you have strings and it’s better to work with numbers (even if it worked without that).

The Math.max and the Math.min accept two (or more) arguments, and return the largest/minor. The .reduce() passes the previous value and the new, 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 least 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

0

I advise you to use the library Lodash. The lib is extremely 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>

0

You have to convert strings into numbers before making 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)

-2

You can use the Math.Max() and the Math.Min() to pick up the values, as it is something relatively simple I’ll just point out the links and let you study =]
This one too

  • We appreciate your willingness to collaborate with the community, but it might be interesting to read the text We want answers that contain only links? The main problem is that if the answer link eventually ceases to exist, the answer completely loses its meaning. To get around this, check with the content of the link the main points that are valid to the question and describe them here, keeping the link only as a support material.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.