Returning max value of array javascript

Golden Panda

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])
);

Yevgen Gorbunkov

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))

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related