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.
In this example, we used the spread(...
) operator with the Math.max()
and Math.min()
for regular arrays:
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
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.
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
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:
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!
Comments