DEV Community

Cover image for 1 line of code: How to get highest numeric item of an Array
Martin Krause
Martin Krause

Posted on • Edited on

1 line of code: How to get highest numeric item of an Array

const biggestItem = arr => Math.max(...arr); 
Enter fullscreen mode Exit fullscreen mode

Returns the highest coerced numerical item of the array.


The repository & npm package

You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.

The code and the npm package will be updated every time I publish a new article.


Follow me on Twitter: @martinkr and consider to buy me a coffee

Photo by zoo_monkey on Unsplash


Top comments (9)

Collapse
 
jrop profile image
Jonathan Apodaca

I'm curious how the performance compares to:

arr.reduce((prev, curr) => Math.max(prev,curr))
Enter fullscreen mode Exit fullscreen mode

Especially in the case of large arrays, I'm not sure what the implications are (if any) to spreading a large array to function arguments

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Try this - the first method seems to be about 10 times as fast

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Interestingly, if you switch to a typed array, the results are reversed - reduce is 10 times as fast on Firefox, and nearly twice as fast on Chrome

Thread Thread
 
jrop profile image
Jonathan Apodaca

And unsurprisingly, this is even faster:

let m = Number.NEGATIVE_INFINITY;
for (const x of data) {
  m = Math.max(x, m);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
martinkr profile image
Martin Krause • Edited

Thank you both for the performance analysis, it's very helpful to have these additional details :)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Probably need to be a bit careful describing what the function does. The function here will actually return the highest coerced numeric value from the array ('biggest' is also slightly ambiguous):

biggestItem([[], "1e6", false, "0xffffff"])   // 16777215
Enter fullscreen mode Exit fullscreen mode

It will also return -Infinity if an empty array is passed, and return NaN if any item in the array cannot be coerced to a Number.

Collapse
 
martinkr profile image
Martin Krause

Thank you for your comment.
I will update the article

Collapse
 
findream profile image
findream

Too boring~! This just is a simple mathematical API.

Collapse
 
mavuriel profile image
mavuriel

Nobody needs your boring and simple comment πŸ₯±, if it's not helpful to you, just ignore that post.