0

I am trying to return the max value of an array in JavaScript without using the Math.max function. Is reduce a good way to do this? My problem is that it is returning 5 not 11 like I want it to. Am I going about this the best way? Could somebody guide me in the right direction.

Here is what I have so far:

function max(arr) {
  return arr.reduce(function(prev, curr) {
    return (prev.value >= curr.value) ? prev : curr;
  });
}

console.log(
  max([3, 1, 2, 7, 11, 3, 4, 5])
);
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34

3 Answers3

3

The elements of your array are not objects (so, they don't have property value which you attempt to evaluate) those are plain numbers, so you may compare each array item with reduce() aggregated parameter directly:

const arr = [3, 1, 2, 7, 11, 3, 4, 5],
      arrMax = arr => arr.reduce((max,n) => n > max ? n : max)
      
console.log(arrMax(arr))
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
  • Essentially the reduce function starts at `arr[0]` and compares to max (`n > max`). If `n > max` is true, `n` is returned (`? n`) as the new max. If not, `max` is retained as the maximum (`: max`). Then it repeats this for `arr[1]`, then `arr[2]` until it gets to the end. @ggorlen Hope this explains it... – Kwame Opare Asiedu Dec 29 '19 at 21:58
0

Array#reduce is the best way to go IMHO but you can still use Math.max to find the biggest number out of the two.

Here's a max function with parameters destructuring so you can do max(10, 42) instead of max([10, 42]) which is closer to the Math.max signature.

const max = (...xs) =>
  xs.reduce((max, x) => Math.max(max, x));
  
console.log(max(3, 1, 2, 7, 11, 3, 4, 5));
//=> 11
customcommander
  • 17,580
  • 5
  • 58
  • 84
-3

I think the best way is to just sort the array and return the first or last value of the array

  function compare(a , b) {
      return  b - a
  }
  let sortedArray = unSortedArray.sort(compare)
  console.log(sortedArray[0])

nibble
  • 384
  • 3
  • 12