YogeshChauhan . com

How to Find the Highest (or Lowest) Number in an Array in JavaScript?

in JavaScript on August 12, 2020

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 function 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
dreamhost

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to uninstall Cocoapods from the Mac OS? #4 How to add Read More Read Less Button using JavaScript? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

May 5 Use inline if to make a shorter conditional syntax in React May 4 What is Conditional Rendering in React? May 3 How does @extend rule work in SCSS (Sass)? May 2 How different is Handling Events in React vs HTML DOM? May 2 How to create bouncing balls using HTML canvas and JavaScript? Apr 30 HTML canvas methods

You might also like these

How to remove border from :visited image, link or button?CSSHow does AdSense calculate page loading time?JavaScriptHow to get category name using post id in WordPress?WordPressObservation of Human Behavior [Shopping Observation Example]MiscWhat’s new in WordPress 5.5?WordPress3 JavaScript methods to use when you want to go back and forth in historyJavaScriptIntroduction to components and templates Part 4: Pipes and DirectivesAngularURL paths in DrupalDrupalWhat is ECMAScript?JavaScriptThe order Property in Flex Items in CSSCSSWhat’s a Web Storage API in JavaScript?JavaScriptPHP Login System using PDO Part 1: Create User Registration PagePHP