JavaScript Program to Find the Maximum and Minimum Element in an Array

Introduction

Finding the maximum and minimum elements in an array is a common task in programming. JavaScript provides methods like Math.max() and Math.min() that allow us to easily determine the largest and smallest numbers in an array. This program demonstrates how to find both the maximum and minimum elements in an array.

Problem Statement

Create a JavaScript program that:

  • Accepts an array of numbers.
  • Finds the maximum and minimum elements in the array.
  • Returns and displays both the maximum and minimum values.

Example:

  • Input: [5, 3, 8, 1, 9]

  • Output: Maximum: 9, Minimum: 1

  • Input: [12, 45, 23, 9]

  • Output: Maximum: 45, Minimum: 9

Solution Steps

  1. Read the Input Array: Provide an array of numbers either as user input or directly in the code.
  2. Find the Maximum and Minimum Elements: Use Math.max() and Math.min() with the spread operator to find the maximum and minimum values.
  3. Display the Result: Print the maximum and minimum values.

JavaScript Program

// JavaScript Program to Find the Maximum and Minimum Element in an Array
// Author: https://www.javaguides.net/

function findMaxMin(arr) {
    // Step 1: Find the maximum element
    let max = Math.max(...arr);

    // Step 2: Find the minimum element
    let min = Math.min(...arr);

    // Step 3: Return the result
    return { max, min };
}

// Example input
let array = [5, 3, 8, 1, 9];
let { max, min } = findMaxMin(array);
console.log(`The maximum element is: ${max}`);
console.log(`The minimum element is: ${min}`);

Output

The maximum element is: 9
The minimum element is: 1

Example with Different Input

let array = [12, 45, 23, 9];
let { max, min } = findMaxMin(array);
console.log(`The maximum element is: ${max}`);
console.log(`The minimum element is: ${min}`);

Output:

The maximum element is: 45
The minimum element is: 9

Explanation

Step 1: Find the Maximum Element

  • The Math.max() function is used with the spread operator (...arr) to find the largest number in the array. The spread operator expands the array into individual elements, allowing Math.max() to operate on them.

Step 2: Find the Minimum Element

  • Similarly, the Math.min() function is used with the spread operator to find the smallest number in the array.

Step 3: Return and Display the Result

  • The function returns an object containing both the max and min values, which are then printed using console.log().

Conclusion

This JavaScript program demonstrates how to find both the maximum and minimum elements in an array using Math.max() and Math.min() with the spread operator. This approach is efficient and handles arrays of any size, making it a versatile solution for finding the largest and smallest values in an array.

Comments