Table of Contents
show
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
Views: 80