JavaScript: Find the Smallest and Biggest Numbers

Niani Byrd
1 min readNov 12, 2021

Let’s solve another problem:

Create a function that takes an array of numbers and return both the minimum and maximum numbers, in that order.

So we are given an array of numbers and we need to return the smallest number and the largest number, in that order. For example, if our array includes

minMax([1, 2, 3, 4, 5, 6, 7]) 

We want to return:

[1, 7]

Start by creating a brand new array. This array is what will be returned after we solve the problem.

function minMax(arr) {
let arr1 = [];
}

The solution is very easy, because we can use two of JavaScript’s built-in functions. To find the smallest number, we use .min. To find the largest number, we use .max. Let’s see what that looks like:

function minMax(arr) {
let arr1 = [];
arr1.push(Math.min(...arr));
arr1.push(Math.max(...arr));
return arr1
}

Take note of two things: we are using .push to push our new values into the array. We are using the spread operator (the three dots before arr) to expand our array into individual elements.

Happy Coding!

--

--