;

How to Find the Min/Max Elements in an Array in JavaScript


Tutorialsrack 27/11/2021 Jquery Javascript

In this article, you’ll learn how to find the min and max elements in an array in javascript. There are various methods to find the smallest and largest numbers in a JavaScript array. JavaScript Math class offers the max() and min() functions, which return the largest and the smallest value among the given numbers, respectively. You can use these methods to find the maximum and minimum in an array.

Here are some examples to find the min and max elements in an array in javascript.

Example 1: Using Spread Operator with Math.max() and Math.min()

In this example, we used the spread(...) operator with the Math.max() and Math.min() for regular arrays:

Example 1: Using Spread Operator with Math.max() and Math.min()
let arrayOfNumbers = [4, 12, 62, 70, -10];
console.log("Max: " + Math.max(...arrayOfNumbers)); 
// output ==> Max: 70

console.log("Min: " + Math.min(...arrayOfNumbers)); 
// output ==> Min: -10

Example 2: apply() function with Math.max() and Math.min()

In this example, we used the Function.prototype.apply() method. For arrays with fewer elements, you can use the Function.prototype.apply() method to find the maximum and minimum value in a numeric array.

Example 2: apply() function with Math.max() and Math.min()
let arrayOfNumbers = [4, 12, 62, 70, -10];

console.log("Max: " + Math.max.apply(Math, arrayOfNumbers)); 
// output ==> Max: 70

console.log("Min: " + Math.min.apply(Math, arrayOfNumbers)); 
// output ==> Min: -10

Example 3: reduce() function with Math.max() and Math.min()

In this example, we used the Array.reduce() method. The approach is recommended to use the Array.reduce() to find the max and min elements in an array. This approach works by comparing each value of the array:

Example 3: reduce() function with Math.max() and Math.min()
const min = arr => arr.reduce((x, y) => Math.min(x, y));
const max = arr => arr.reduce((x, y) => Math.max(x, y));
 
let arrayOfNumbers = [4, 12, 62, 70, -10];

console.log("Max:" + max(arrayOfNumbers));
// output ==> Max: 70

 
console.log("Min:" + min(arrayOfNumbers));
// output ==> Min: -10

I hope this article will help you to understand how to find the min and max elements in an array in javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags