Files
30-seconds-of-code/blog_posts/js-array-min-max.md
Isabelle Viktoria Maciohsek 9482b077ec Bake dates into articles
2021-06-13 19:52:48 +03:00

1.1 KiB

title, type, tags, authors, cover, excerpt, firstSeen, lastUpdated
title type tags authors cover excerpt firstSeen lastUpdated
Tip: Min and max value in a JavaScript array tip javascript,array,math chalarangelo blog_images/little-tree.jpg When working with numeric arrays in JavaScript, you might find yourself in need of finding the minimum or maximum value. Here's a quick and easy way to do it. 2021-03-01T11:00:00+02:00 2021-06-12T19:30:41+03:00

When working with numeric arrays in JavaScript, you might find yourself in need of finding the minimum or maximum value. Luckily, JavaScript's Math built-in object has got you covered. You can simply use Math.min() or Math.max() combined with the spread operator (...), as both functions accept any number of arguments.

const nums = [2, 4, 6, 8, 1, 3, 5, 7];

Math.max(...nums); // 8
Math.min(...nums); // 1

For more complex cases (i.e. finding the min/max value in an array of objects), you might have to resort to Array.prototype.map() or Array.prototype.reduce(), but our minBy or maxBy snippets might be all you need.