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

Recently Posted

#Dec 4 What is Etrieve Flow? #Dec 2 The unique operator($) in Envision Basic #Nov 25 Steps to Install Microsoft SQL Server on a MacOS #Nov 11 What is DevOps? #Nov 10 The * arithmetic operator in Envision Basic #Nov 10 What are Big Data Clusters in SQL Server?
You might also like these
How to change value of a span tag using a reference from another div using jQuery?jQuerySorting Object Arrays in JavaScriptJavaScriptHow to set up the local environment and workspace for Angular development?AngularUNION and UNION ALL in PostgresPostgresCreate a galley with overlapping images using CSS gridCSSRIGHT JOIN in PostgresPostgresWhat is a “promise” in JavaScript?JavaScriptAn Example of Cross-site Scripting (XSS) Attack in PHP and How to Avoid It?PHPOptional arguments, Default parameters and REST parameters in JavaScriptJavaScriptHow to make a Custom Login Page in WordPress?WordPressHow to create a pricing table using flex in CSS?CSSHow to Find the Highest (or Lowest) Number in an Array in JavaScript?JavaScript