I’m working with arrays in JavaScript and need to find the smallest and largest numbers efficiently. I know there are several ways to do this but I’m looking for the most straightforward approach.
For example, if I have an array like this:
let numbers = [25, 3, 78, 12, 99]
// I want something like:
getMinValue(numbers) // should return 3
getMaxValue(numbers) // should return 99
What’s the best method to achieve this? I’ve heard about using Math functions but I’m not sure about the exact syntax. Any help would be appreciated!
To find the minimum and maximum values from an array in JavaScript, you can effectively use the spread operator along with the Math.min() and Math.max() functions. Here’s a simple example:
let numbers = [25, 3, 78, 12, 99];
let minValue = Math.min(...numbers); // this will return 3
let maxValue = Math.max(...numbers); // this will return 99
Make sure to be cautious with very large arrays, as passing too many arguments can lead to a stack overflow error. However, for most applications, this method is both efficient and straightforward.
You can also use a simple loop to go through the array once. This works better for huge arrays where the spread operator might slow things down:
function findMinMax(arr) {
let min = arr[0];
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < min) min = arr[i];
if (arr[i] > max) max = arr[i];
}
return { min, max };
}
This runs in O(n) time and won’t hit stack overflow errors with large datasets. It’s memory efficient too - just needs two variables no matter how big your array is.
u can also use sort() if u dont mind changin the original array. just do numbers.sort((a,b) => a-b) - first element becomes min, last becomes max. its slower but works fine for smaller arrays.