Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 23, 2022 05:10 pm GMT

Finding the Minimum and Maximum Values of an Array in JavaScript

singularity
In javascript it is possible to find the minimum and maximum value of an integer in an array

This is among the most common coding interview question that interviewers use to test the skills of developers.

Chapter 1 Using in built library

The simplest method of finding the minimum value of an array is by using the in built Math library that has both Math.min and Math.max functions for finding minimums and maximums.

//Find the maximum in an arraylet maxValue = Math.max(...arr);//Find the minimum in an arraylet minValue = Math.min(...arr);

Chapter 2 Using in for loops

One can also accomplish this by the use of a for loop as shown

//Find the maximum in an arrayfunction arrMax(arr) {  let maxArr = Number.NEGATIVE_INFINITY;  for (let i = 0; i < arr.length; i++) {    if (arr[i] >= maxArr) {      maxArr = arr[i];    }  }}

The same can be used in finding the smallest number

//Find the minimum in an arrayfunction arrMin(arr) {  let minArr = Number.POSITIVE_INFINITY;  for (let i = 0; i < arr.length; i++) {    if (arr[i] <= minArr) {      minArr = arr[i];    }  }}

Number.NEGATIVE_INFINITY and Number.POSITIVE_INFINITY are used in javascript to represent the lowest and highest number representation of the language.

Chapter 3 Using in reduce function

Alternatively, one may opt to use the Array.prototype.reduce() function in finding the minimum and maximum values of an array. The reduce function simply uses a provided callback to return a single element. In our case, this is either the minimium value or the maximum value.

//Find the minimum in an arrayfunction arrMin(arr) {  return arr.reduce((a, b) => (a < b ? b : a));}
//Find the maximum in an arrayfunction arrMax(arr) {  return arr.reduce((a, b) => (a < b ? a : b));}

The (a, b) => (a < b ? b : v) expression works as an if.. else statement. In javascript it is referred to as the Ternary operator with a method signature as

variable = Expression1 ? Expression2: Expression3

Leave a like if you found this useful
Happy coding


Original Link: https://dev.to/cavein254/finding-the-minimum-and-maximum-values-of-an-array-in-javascript-3kel

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To