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

amazon

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 add Read More Read Less Button using JavaScript? #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

#Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS? #Aug 1 What is Zdog? #Aug 1 How to add before after image effect using pure CSS? #Jul 31 Add animation to your skills bar using CSS #Jul 31 Use SwiperJS to create mobile touch sliders fast
You might also like these
How to get ACF values from custom post type?WordPressClean Form Input With These PHP Functions Before Inserting into DatabasePHPSubquery in PostgresPostgresHow to create a horizontal scrolling menu with and without flex using CSS (or SCSS)?CSSCROSS JOIN in PostgresPostgresHow to compress images with gulp in WordPress?WordPressMicroservices vs Monolithic ArchitectureMiscellaneousNew to  Drupal? Here’s What You Need to KnowDrupalWordPress: How to find all posts with a specific custom field value?WordPressExplanation of PostgreSQL PgAdmin interfacePostgresWordPress get_posts ExamplesWordPressA Quick Comparison of JOIN and Subquery in SQLSQL/MySQL