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

6 4

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

Visualizing Promises and Async/Await 🤯

async await

Learn the ins and outs of Promises and Async/Await!

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay