DEV Community

Cover image for Getting the min or max value from an array of numbers in javascript
Nick Raphael
Nick Raphael

Posted on • Edited on

Getting the min or max value from an array of numbers in javascript

Turns out this is simple. Well, it was simple anyway, but it's also quite concise.

I'll provide my code examples in javascript.

Let's suppose we have an array of number...

var myNumbers = [100, 50, 200];
Enter fullscreen mode Exit fullscreen mode

We can use swanky destructuring assignment, which I know more commonly as the spread operator.

var myNumbers = [100, 50, 200];
var myMinNumber = Math.min(...myNumbers);
var myMaxNumber = Math.max(...myNumbers);
Enter fullscreen mode Exit fullscreen mode

Short and sweet.

Top comments (6)

Collapse
 
andypotts profile image
Andy Potts

I think there's a typo, "nums" should be "myNumbers" :)

E.g.

var myNumbers = [100, 50, 200];
var myMinNumber = Math.min(...myNumbers);
var myMaxNumber = Math.max(...myNumbers);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nickraphael profile image
Nick Raphael

Thank you!!! Fixed.

Collapse
 
superturkey650 profile image
Jared Mosley • Edited

In case you want to be able to switch how you compare the items, you can also do something like this:

const compare = (a, b) => a > b;
const min = arr.reduce((acc, val) => compare(acc,val) ? val : acc);
const max = arr.reduce((acc, val) => compare(acc,val) ? acc : val);
Collapse
 
nombrekeff profile image
Keff

Nice snippet, I always forget about min and max :)

Collapse
 
damxipo profile image
Damian Cipolat

Wow nice!

Collapse
 
shkarsardar profile image
Shkarsardar

excellent