#### Interview Question #5:

Write a function that will return the min and max numbers in an array βπ€

If you need practice, try to solve this on your own. I have included 3 potential solutions below.

Note: There are many other potential solutions to this problem.

Feel free to bookmark π even if you don't need this for now. You may need to refresh/review down the road when it is time for you to look for a new role.

Code: https://codepen.io/angelo_jin/pen/zYzvQdM

#### Solution #1: Math Methods - min and max

- Spread the array to Math methods like below and we are set

```
function getMinMax(arr) {
return {
min: Math.min( ...arr ),
max: Math.max( ...arr )
}
}
```

#### Solution #2: Array Sort

- Sort the array first using an efficient merging algorithm of choice. Once sorting is done, the first element would be the minimum and the last would be the maximum.

```
function getMinMax(arr) {
const sortedArray = arr.sort((a, b) => a - b)
return {
min: sortedArray[0],
max: sortedArray[sortedArray.length - 1]
}
}
```

#### Solution #3: for of loop

- Below solution will use two variables and will compare each array elements and assign it to min and max if it meets the condition accordingly.

```
function getMinMax(arr) {
let min = arr[0];
let max = arr[0];
for (let curr of arr) {
if (curr > max) {
max = curr;
}
if (curr < min) {
min = curr;
}
}
return {
min,
max
};
}
```

Happy coding and good luck if you are interviewing!

If you want to support me - Buy Me A Coffee

In case you like a video instead of bunch of code ππ

## Top comments (2)

This response would get them a second look in an interview IMHO. :)

They understand const, lambda functions, Array.reduce, comparisons with

undefined, it handles the empty array case without crashing, and performs okaycrazy snippet! They might just hire you if you can code and explain this well on the interview. Thanks for the code!