Add JS array min max

This commit is contained in:
Chalarangelo
2021-03-01 05:00:00 -04:00
parent d4abc910af
commit 61691099f3
2 changed files with 21 additions and 0 deletions

BIN
blog_images/little-tree.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

View File

@ -0,0 +1,21 @@
---
title: "Tip: Min and max value in a JavaScript array"
type: tip
tags: javascript,array,math
authors: chalarangelo
cover: blog_images/little-tree.jpg
excerpt: 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.
---
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.
```js
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](/js/s/min-by) or [maxBy](/js/s/max-by) snippets might be all you need.
**Image credit:** [Luke Porter](https://unsplash.com/@lukeporter?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)