how to return the max and min of an array in javascript
How to Return the Max and Min of an Array in JavaScript
If you have an array of numbers in JavaScript and you want to find the maximum and minimum values, there are several ways to do it. Here are a few methods:
Method 1: Using Math.max() and Math.min()
The simplest way is to use the built-in Math.max() and Math.min() functions in JavaScript. These functions take any number of arguments and return the maximum or minimum value.
var numbers = [1, 2, 3, 4, 5];
var max = Math.max.apply(null, numbers);
var min = Math.min.apply(null, numbers);
In the above code, we first define an array of numbers. We then use the apply() method to call the Math.max() and Math.min() functions with the numbers array as arguments. The null argument is used to set the this value inside the called function to the global object.
Method 2: Using a For Loop
We can also find the maximum and minimum values of an array using a for loop. Here's an example:
var numbers = [1, 2, 3, 4, 5];
var max = -Infinity;
var min = Infinity;
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
if (numbers[i] < min) {
min = numbers[i];
}
}
In the above code, we first define an array of numbers. We then loop through each element of the array using a for loop. Inside the loop, we check if the current number is greater than the current maximum or less than the current minimum. If it is, we update the max or min variable.
Method 3: Using the Spread Operator
Finally, we can use the spread operator (...) to pass the array elements as arguments to the Math.max() and Math.min() functions. Here's an example:
var numbers = [1, 2, 3, 4, 5];
var max = Math.max(...numbers);
var min = Math.min(...numbers);
In the above code, we use the spread operator to pass each element of the numbers array as an argument to the Math.max() and Math.min() functions. This is equivalent to calling the functions with each element of the array as a separate argument.