find the largest element in an array in typescript

To find the largest element in an array in TypeScript, we can use a loop and a conditional statement to compare each element in the array to the current largest value and update the largest value accordingly. Here is an example function that takes an array of numbers and returns the largest element:

index.ts
function findLargestElement(arr: number[]): number {
  if (arr.length === 0) {
    throw new Error("Array is empty");
  }
  
  let largest = arr[0];
  
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] > largest) {
      largest = arr[i];
    }
  }
  
  return largest;
}
278 chars
16 lines

In this function, we first check if the array is empty and throw an error if it is. Then, we set the largest variable to the first element of the array. We then loop through the rest of the elements in the array and compare each one to the current largest value. If we find an element that is larger, we update largest to be that element instead. Finally, we return largest.

We can call this function with an array of numbers like this:

index.ts
const myArray: number[] = [1, 5, 3, 9, 2];
const largestElement = findLargestElement(myArray);
console.log(largestElement); // Output: 9
137 chars
4 lines

This will output the largest element in the array, which is 9.

gistlibby LogSnag