DEV Community

Discussion on: What´s wrong with Array.reduce ?

lukaszahradnik profile image
Lukáš Zahradník

Math.max exists

wulymammoth profile image

numbers.reduce((max, num) => Math.max(max, num), 0)

Thread Thread
avalander profile image
Avalander • Edited on

Edit: also note that your implementation is incorrect. If all numbers are negative, the function will return 0 even if it is not in numbers. The starting value should be -Infinity.

Thread Thread
wulymammoth profile image
David • Edited on

Fair points, but it's not "wrong". My intention was to set a floor, though, not explicitly stated. The initial value matters. Although, your suggestion is the same as mine, because your floor is -Infinity. To derive the min, we don't need an initial value at all -- it's optional. The only instance in which that wouldn't work is an empty array - sort of the case I was covering :)

Now, let's write some unit-tests to document :)

savagepixie profile image

Math.max(...nums) for the win