EN
TypeScript - max value in array
3
points
In this article, we would like to show you how to find maximum value in array in TypeScript.
Quick solution:
const numbers: number[] = [2, 3, 1];
const max: number = Math.max(...numbers);
console.log(max); // 3
Reusable logic
const findMax = (array: number[]): number => {
if (array.length === 0) {
return NaN;
}
let result = array[0];
for (let i = 1; i < array.length; ++i) {
const entry = array[i];
if (entry > result) {
result = entry;
}
}
return result;
};
// Usage example:
const max = findMax([2, 3, 1]);
console.log(max); // 3
Output:
3