Programming with JavaScript

⌘K
  1. Home
  2. Docs
  3. Programming with JavaScri...
  4. Example Programs
  5. Find Max Min

Find Max Min

Example 34

Write a function to find maximum and minimum number in an array

function findMaxMin(numbers) {
  if (numbers.length === 0) {
    return { max: undefined, min: undefined };
  }

  let max = numbers[0];
  let min = numbers[0];

  for (let i = 1; i < numbers.length; i++) {
    if (numbers[i] > max) {
      max = numbers[i];
    }
    if (numbers[i] < min) {
      min = numbers[i];
    }
  }

  return { max, min };
}

let numbersArray = [5, 12, 3, 9, 7, 1, 15];
let result = findMaxMin(numbersArray);

console.log("Maximum value:", result.max);
console.log("Minimum value:", result.min);

Output

Loading

Views: 80

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments