DEV Community

Drozerah
Drozerah

Posted on

4

Find the largest number in an Array - one line

Spread that out !

Top comments (4)

Collapse
 
jdforsythe profile image
Jeremy Forsythe

jsbench.me/g4jx2nffbo/1

Array.prototype.reduce() seems to be much faster.

array.reduce((acc, val) => val > acc ? val : acc);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
drozerah profile image
Drozerah • Edited
console.time('first')
    Math.max(...array)
console.timeEnd('first') // first: 0.179ms

console.time('second')
    array.reduce((acc, val) => val > acc ? val : acc)
console.timeEnd('second') // second: 0.054ms

Definitively slower to execute but half the time to write it :)

Collapse
 
georgecoldham profile image
George

Depends what the codes for really.

Math.max() is easier to read, and if only run occasionally on small arrays... fine.

Reduce is a little more convoluted, but still can be understood easily enough. The time savings on the code if running frequently or on larger datasets can quickly add up in benefits.

Collapse
 
jdforsythe profile image
Jeremy Forsythe

Not if you use snippets!

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay