Yogesh Chauhan's Blog

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

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to Install PHP Laravel on MacOS Catalina?PHPAll possible ways you can Insert Data in PostgresPostgresReverse a String in JavaScriptJavaScript3 Types of Arrays in PHPPHPValues and Types Basics in JavaScriptJavaScriptWindow setInterval() Method in JavaScriptJavaScriptHow to create a smooth scrolling effect with CSS?CSSClearwater Seafoods – B2C in ChinaMiscellaneousHow to add a ribbon on top of a container using CSS?CSSHow to create a simple tab interaction using CSS?CSSJavaScript Data Types and Data Structures Things to RememberJavaScriptHow to import a CSS file using PHP code and not HTML code?PHP