We saw the compare() and sort() function in details in this blog post:

The Sort And Compare Functions In JavaScript

We can use the same functon to sort the numbers and then use the first and last numbers as min and max. It's a work around but it works.


var points = [40, 100, 1, 5, 25, 10];
points.sort(function (a, b) {
  return a - b;
});

console.log("lowest value = " + points[0]);
console.log("highest value = " + points[points.length - 1]);

// lowest value = 1
// highest value = 100

We can use the same trick with sorting the array in descending:


var points = [40, 100, 1, 5, 25, 10];
points.sort(function (a, b) {
  return b - a;
});

console.log(" highest value = " + points[0]);
console.log("lowest value = " + points[points.length - 1]);

// highest value = 100
// lowest value = 1

0 Comments

Leave a reply

Your email address will not be published. required fields are marked *