I want to create function that will find highest/maximum value from an array of values.
For example: numbers = [2, 24, 48, 9, 15, 41].
How can it be done other than using Math.max()?
3 Answers
Try this:
function maxVal(array){
let indexOfMax = 0;
for (let i = 0; i < array.length; i++){
if (array[i] > array[indexOfMax]){
indexOfMax = i;
}
}
return array[indexOfMax];
}
3 Comments
Simply use Array.prototype.reduce, it's usually the smartest way for doing simple math operations like getting averages, ranges or min-max
function max(...values) {
return values.reduce((prev, curr) => curr > prev ? curr : prev)
}
// or without the `...rest` parameter to use an array directly
function maxFromArr(values) {
return values.reduce((prev, curr) => curr > prev ? curr : prev)
}
with this you have some clean and efficient code:
max(1, 2, 3, 8, 435, 32, 0) // => 432
// or for an array
const arr = [1, 2, 3, 72, 32, 0]
maxFromArray(arr) // => 74
// or
max(...arr) // => 74
Common Pitfall
When comparing numbers, usually always test for a positive (is instead of isNot)
Testing for a positive result (is the current larger ? use current, instead of is the current smaller ? use previous) will also automatically take care of any item that can't be turned into a proper number (comparing a number to NaN will always return false. eg. 12 < NaN and 12 > NaN both return false).
If you do it the other way around you might get a surprising result: (feel free to run this snippet in any playground)
function max (...values: number[]) {
return values.reduce((prev, curr) => curr > prev ? curr : prev)
}
function naïveMax (...values: number[]) {
// notice were testing for a negativ: is the current smaller ?
// if it **isn't**, use the current
return values.reduce((prev, curr) => curr < prev ? prev : curr)
}
const arr1 = [1, 21, 3, 12, 2]
console.log(max(...arr1)) // => 21
console.log(naïveMax(...arr1)) // => 21
// looking good so far
const arr2 = [89, -21, 32, {}, 342]
console.log(max(...arr2)) // => 342
console.log(naïveMax(...arr2)) // => 242
// looks still ok, despite an object being mixed in, but
const arr3 = [64, 2, 3, 95, 32, {}]
console.log(max(...arr3)) // => 95
console.log(naïveMax(...arr3)) // => {}
// whoops, the largest number suddenly is the object
here's min for completeness sake
function min(...values) {
// again, test for a positive to filter `NaN`-values
return values.reduce((prev, curr) => curr < prev ? curr : prev)
}
Comments
const getHighest = numbers.sort((a, b) => b-a)[0];
forloop,forEach,reduce...-Infinity.