DEV Community

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

Collapse
lukaszahradnik profile image
Lukáš Zahradník

Math.max exists

Collapse
wulymammoth profile image
David

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

Thread Thread
avalander profile image
Avalander • Edited on
Math.max(...numbers)

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

Collapse
savagepixie profile image
SavagePixie

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