## DEV Community π©βπ»π¨βπ»

Let's Code

Posted on • Updated on

# JS Coding Question #5: Find Min and Max [3 Solutions]

#### 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.

#### 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)

Tony B

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 okay

``````const minmax = arr => arr.reduce((a,c) => {
a.min = a.min < c ? a.min : c;
a.max = a.max > c ? a.max : c;
return a;
}, {});
``````

Let's Code

crazy snippet! They might just hire you if you can code and explain this well on the interview. Thanks for the code!

## π Friends don't let friends browse without dark mode.

Sorry, it's true.