find the smallest element in an array in typescript

To find the smallest element in an array in TypeScript, you can use the Math.min function and the spread operator ... to pass in the array elements as arguments. Here is an example:

index.ts
const array: number[] = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];

const smallest: number = Math.min(...array);

console.log(smallest); // output: 1
142 chars
6 lines

In this example, we have an array of numbers called array. We then use the Math.min function and the spread operator ...array to pass in the array elements as arguments to the Math.min function. This function returns the smallest element from the array, which we then store in a variable called smallest. Finally, we print the value of smallest to the console.

Note that this approach assumes that the array has at least one element. If the array is empty, the Math.min function will return Infinity. To handle this case, you can add a check for the length of the array before calling the Math.min function.

gistlibby LogSnag