There are no built-in functions for finding the max or min value in an array.
However, after you have sorted an array, you can use the index to obtain the highest and lowest values.
Sorting ascending:
Example
points.sort(function(a, b){return a - b});
// now points[0] contains the lowest value
// and points[points.length-1] contains the highest value
Sorting descending:
Example
points.sort(function(a, b){return b - a});
// now points[0] contains the highest value
// and points[points.length-1] contains the lowest value
Using Math.max() on an Array
You can use Math.max.apply
to find the highest number in an array:
Example
return Math.max.apply(null, arr);
}
Math.max.apply(null, [1, 2, 3])
is equivalent to Math.max(1, 2, 3)
.
Using Math.min() on an Array
You can use Math.min.apply
to find the lowest number in an array:
Example
return Math.min.apply(null, arr);
}
Math.min.apply(null, [1, 2, 3])
is equivalent to Math.min(1, 2, 3)
.
My Min / Max JavaScript Methods
The fastest solution is to use a "home made" method.
This function loops through an array comparing each value with the highest value found:
Example (Find Max)
let len = arr.length;
let max = -Infinity;
while (len--) {
if (arr[len] > max) {
max = arr[len];
}
}
return max;
}
This function loops through an array comparing each value with the lowest value found:
Example (Find Min)
let len = arr.length;
let min = Infinity;
while (len--) {
if (arr[len] < min) {
min = arr[len];
}
}
return min;
}
Practice Excercise Practice now