Min Max finder in an array of numbers
javascript
Instructions:
Create a function called minMax()
that takes in an array of numbers and returns an object with the minimum and maximum numbers in the array.
Expected result:
minMax([2, 9, 5, 3, 8, 0]);
// Min: 0 and Max: 9
Solution:
function minMax(numbers) {
if (Array.isArray(numbers)) {
const min = Math.min(...numbers);
const max = Math.max(...numbers);
return { min, max };
}
return 'Not a valid array';
}
const {min, max} = minMax([2, 9, 5, 3, 8, 0]);
console.log(`Min: ${min} and Max: ${max}`);
Same solution using arrow function:
const minMax = (numbers) =>
Array.isArray(numbers)
? { min: Math.min(...numbers), max: Math.max(...numbers) }
: "Not a valid array";
const { min, max } = minMax([2, 9, 5, 3, 8, 0]);
console.log(`Min: ${min} and Max: ${max}`);
Test Values:
const { min, max } = minMax([2, 9, 5, 3, 8, 0]);
console.log(`Min: ${min} and Max: ${max}`);
Output:
Min: 0 and Max: 9
const { min, max } = minMax([21, 19, 50, -3, -8, 0]);
console.log(`Min: ${min} and Max: ${max}`);
Output:
Min: -8 and Max: 50