How can I easily obtain the min or max element of a JavaScript array? Example pseudocode: let array = [100, 0, 50] array.min() //=> 0 array.max() //=> 100

 

In JavaScript, you can obtain the minimum and maximum elements of an array using the Math.min() and Math.max() functions along with the spread operator (...) to spread the array elements as function arguments. You can also achieve this using the Array.prototype.reduce() method.

Here's an example using both approaches:

javascript
let array = [100, 0, 50]; // Using Math.min() and Math.max() let minValue = Math.min(...array); let maxValue = Math.max(...array); console.log("Using Math.min():", minValue); // Output: 0 console.log("Using Math.max():", maxValue); // Output: 100 // Using Array.prototype.reduce() let minWithReduce = array.reduce((min, currentValue) => { return Math.min(min, currentValue); }, Infinity); let maxWithReduce = array.reduce((max, currentValue) => { return Math.max(max, currentValue); }, -Infinity); console.log("Using reduce() for min:", minWithReduce); // Output: 0 console.log("Using reduce() for max:", maxWithReduce); // Output: 100

In the above example, the spread operator (...array) is used to pass the individual array elements as arguments to Math.min() and Math.max(). The reduce() method iterates through the array, updating the minimum and maximum values as it goes.

Both approaches will give you the minimum and maximum elements of the array. Choose the one that you find more readable and suitable for your coding style.

Comments