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.ts142 chars6 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