🟨 JavaScript
Easy
🕐 10 min

Maximum and minimum value

Goal: create a function minMax(arr) that returns an object with the minimum and maximum value from the array.

💡 Solution hint
  • Use built-in functions Math.min and Math.max
  • Or a single pass through the array, comparing element values
👀 Solution #1 (single pass)
/**
 * minMax(arr): returns an object with the minimum and maximum value of the array.
 * Examples:
 *   minMax([1, 2, 3]) -> { min: 1, max: 3 }
 *   minMax([-5, 0, 10]) -> { min: -5, max: 10 }
 * @param {number[]} arr — input array of numbers
 * @returns {{ min: number, max: number }}
 */
function minMax(arr) {
  let min = arr[0]; // Initialize minimum with first element
  let max = arr[0]; // Initialize maximum with first element
  
  // Iterate through the array starting from the second element
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < min) min = arr[i]; // Update minimum if necessary
    if (arr[i] > max) max = arr[i]; // Update maximum if necessary
  }
  
  return { min, max }; // Return result as an object
}

Why this approach:

  • Optimal in memory and time — only one pass through the array.
👀 Solution #2 (Math.min / Math.max)
function minMax(arr) {
  return {
    min: Math.min(...arr),
    max: Math.max(...arr)
  };
}

Why this approach:

  • Short and clear.
  • Uses standard JavaScript methods.
  • For large arrays (e.g., 100,000+ elements) may be slower than a loop.
👀 Solution #3 (reduce)
function minMax(arr) {
  return arr.reduce((acc, val) => {
    if (val < acc.min) acc.min = val;
    if (val > acc.max) acc.max = val;
    return acc;
  }, { min: arr[0], max: arr[0] });
}

Why this approach:

  • Functional style with reduce
  • Suitable if you prefer working with iterators.

Task Description

Write a function minMax that returns an object with the minimum and maximum value from the array.

Usage Examples

minMax([1, 2, 3]); // { min: 1, max: 3 }
minMax([-5, 0, 10]); // { min: -5, max: 10 }

Requirements

  • Function must be named minMax
  • Return an object with keys min and max
  • Work for any numbers, including negative ones
  • Do not modify the input array

🧑‍💻 It's not a bug! It's a feature!

The code editor is intentionally hidden on mobile.

Believe me, it's for the best: I am protecting you from the temptation to code in less-than-ideal conditions. A small screen and a virtual keyboard are not the best tools for a programmer.

📖 Now: Study the task, think through the solution. Act like a strategist.

💻 Later: Sit down at your computer, open the site, and implement all your ideas comfortably. Act like a code-jedi!