Q:

How to Find the Max and Min Values of an Array in JavaScript

0

How to Find the Max and Min Values of an Array in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the apply() Method

You can use the Math.max() and Math.min() methods in combination with the apply() method to find the maximum or minimum values within an array or an array-like object, like this:

<script>
var numbers = [1, 5, 2, -7, 13, 4];
    
var maxValue = Math.max.apply(null, numbers);
console.log(maxValue); // Prints: 13
    
var minValue = Math.min.apply(null, numbers);
console.log(minValue);  // Prints: -7
</script>

See the tutorial on JavaScript borrowing methods to know the reason for using the apply() method here. Alternatively, you can use the ES6 spread operator to perform the same task.

<script>
var numbers = [1, 5, 2, -7, 13, 4];
    
var maxValue = Math.max(...numbers);
console.log(maxValue); // Prints: 13
    
var minValue = Math.min(...numbers);
console.log(minValue);  // Prints: -7
</script>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Check If an Object Property is Undefined in... >>
<< How to Add a Class to a Given Element in JavaScrip...