Find the Minimum and Maximum Element in an Array Using TypeScript

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.

Cialis (Tadalafil) är den främsta konkurrenten till Viagra (Sildenafil) på marknaden för erektil dysfunktion. köpa Cialis i Sverige föredras av många på grund av sin längre varaktighet och anses vara det mest kostnadseffektiva varumärkesbaserade ED-läkemedlet som finns tillgängligt i Sverige. Cialis finns i två varianter: Cialis och Cialis Daily, och fyra olika doseringar: 2,5 mg, 5 mg, 10 mg och 20 mg, erbjuder Cialis också en rad olika alternativ för att passa patientens behov.