/
/
How to get the highest or the lowest value in an array
Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Share on email

How to get the highest or the lowest value in an array

To get the maximum or the minimum value from an array, we can use Math.max() and Math.min() and pass as arguments the numbers from which we want to pick.
For example, we can use the same menu order from above and try to determine the most expensive and the cheapest item from the order.
const menuOrder = [
  { name: "Spaghetti", price: 10 },
  { name: "Pizza", price: 8 },
  { name: "Wine", price: 50 },
];

// the most expensive
Math.max(...menuOrder.map((item) => item.price));

// the cheapest
Math.min(...menuOrder.map((item) => item.price
It works by creating an array with all the prices, and then it uses the spread syntax to expand the array into values that are then passed to the Math.max() or Math.min() functions.

Recent Posts

Branding Strategies Guide to Stand Above the Developers Crowd

Do you want to build a personal brand and increase your social media presence as a developer? Then this guide is for you! Learn how to do it today.

30 Useful JavaScript Array Methods You Must Know

If you want to get a deeper understanding of arrays and how they work in your Javascript code, this is the article for you!

Take-Home Coding Challenges: Everything You Need To Know To Ace Them

This blog post will give you the rundown on the do’s and don’ts of take-home coding challenges, as well as some tips to help you ace them!