Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get max / min from array of strings (javascript)

Tags:

javascript

Any ideas to calculate min / max from array of strings?

var arr = ['aab','aac','aad','abx'];

So far i have considered to use .sort() function depending max / min, and get first element of result.

But maybe you know better preforming solution?

EDIT: Array size is below 1k elements. By Min /max i meant alphabetic sort: first and last element.

like image 305
IT Man Avatar asked Jul 09 '26 23:07

IT Man


1 Answers

To extend @Keith's answers.. if we want min or max only then reduce will be 1-liner.

const arr = ['aab', 'aac', 'aad', 'abx']
const min = arr.reduce((min, c) => c < min ? c : min) // 'aab'
const max = arr.reduce((max, c) => c > max ? c : max) // 'abx'
like image 54
rsinha Avatar answered Jul 11 '26 11:07

rsinha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!