How to Find the Min/Max Elements in an Array in JavaScript
There are multiple methods to find the smallest and largest numbers in a JavaScript array, and the performance of these methods varies based on the number of elements in the array. Let’s discuss each of them separately and give the testing results in the end.
Math.max()
For regular arrays you can use the Math.max with three dots:
let max = Math.max(...arrayOfNumbers);
Example:
Using the three dots (…) makes it easy to call any function expecting arguments.
apply()
The Math.max function uses the apply() method to find the maximum element in a numeric array:
Math.min.apply(Math, testArr);
Math.max.apply(Math, testArr);
Example:
The spread operator
The spread operator is also used to get the maximum of an array. It expands an array of numbers into the list of arguments, such as with Math.min() and Math.max() :
Math.min(...testArr);
Math.max(...testArr);
Math.min.apply(Math, testArr);
Math.max.apply(Math, testArr);
The standard loop
You can use the standard loop for tons of arguments as for loop doesn’t have size limitation:
let max = testArray[0];
for (let i = 1; i < testArrayLength; ++i) {
if (testArray[i] > max) {
max = testArray[i];
}
}
let min = testArray[0];
for (let i = 1; i < testArrayLength; ++i) {
if (testArray[i] < min) {
min = testArray[i];
}
}
Example:
reduce()
You can also use the reduce() method for getting the number of items:
testArr.reduce(function (a, b) {
return Math.max(a, b);
});
testArr.reduce(function (a, b) {
return Math.min(a, b);
});
Example:
Maximum Size of the Array
The apply and spread methods had a limitation of 65536 which came from the limit of the maximum number of arguments. In 2019, the limit is the maximum size of the call stack, meaning that the maximum size for the numbers in case of apply and spread solutions is approximately 120000. The following script will calculate the limit for your particular environment:
let testArr = Array.from({
length: 10000
}, () => Math.floor(Math.random() * 2000000));
for (i = 10000; i < 1000000; ++i) {
testArr.push(Math.floor(Math.random() * 2000000));
try {
Math.max.apply(null, testArr);
} catch (e) {
console.log(i);
break;
}
}
When you test all the given examples above, the results show that the standard loop is the fastest. Then come the apply and spread methods, after them comes the reduce, which is the slowest one. When dealing with large arrays of more than 40 elements, the spread operator is considered a worse choice compared to other methods.