To get the highest or lowest number from an array in JavaScript, you can use the Math.max()
or the Math.min()
methods then spread the elements from the array to these methods using the spread operator (...
).
Consider this array of numbers,
// number array const numberArr = [23, 122, 1, 23, 4, 56];
Now let's use the Math.max()
and Math.min()
methods and use the spread operator on the array like this,
// number array const numberArr = [23, 122, 1, 23, 4, 56]; // get highest number const highest = Math.max(...numberArr); // get lowest number const lowest = Math.min(...numberArr); console.log("Highest Number: " + highest); // Highest Number: 122 console.log("Lowest Number: " + lowest); // Lowest Number: 1
- Both the methods
Math.max()
andMath.min()
returns a number.
See the above example live in JSBin.
Top comments (1)
Awesome!!!