Here are two ways to find the minimum and maximum element in an array using TypeScript:
1. Using Math.min and Math.max:
function findMinMax<T>(arr: T[]): [T, T] {
const min = Math.min(…arr);
const max = Math.max(…arr);
return [min, max];
}
const numbers = [1, 5, 2, 8, 3];
const [minNumber, maxNumber] = findMinMax(numbers);
console.log(`Minimum number: ${minNumber}`);
console.log(`Maximum number: ${maxNumber}`);
Explanation:
1. This method utilizes the built-in `Math.min` and `Math.max` functions.
2. The spread operator (`…`) is used to expand the array elements as individual arguments to these functions.
3. The function returns an array containing the minimum and maximum values.
2. Using a loop:
function findMinMax<T>(arr: T[]): [T, T] { let min = arr[0]; let max = arr[0]; for (const element of arr) { if (element < min) { min = element; } if (element > max) { max = element; } } return [min, max]; } const numbers = [1, 5, 2, 8, 3]; const [minNumber, maxNumber] = findMinMax(numbers); console.log(`Minimum number: ${minNumber}`); console.log(`Maximum number: ${maxNumber}`);
Explanation:
1. This method iterates through the array using a loop.
2. It initializes `min` and `max` with the first element and compares each subsequent element with them.
3. It updates `min` and `max` if a smaller or larger element is found, respectively.
4. The function returns an array containing the minimum and maximum values.