DEV Community

Cover image for JS Coding Question #5: Find Min and Max [3 Solutions]
Let's Code
Let's Code

Posted on • Edited on

3 1

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.

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 )
  }
}
Enter fullscreen mode Exit fullscreen mode

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]
  }
}
Enter fullscreen mode Exit fullscreen mode

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
  };
}
Enter fullscreen mode Exit fullscreen mode

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 👍😊

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (1)

Collapse
 
frontendengineer profile image
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!

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay