To find the range of all elements in an array in TypeScript, you need to first calculate the minimum and maximum values of the elements in the array, and then subtract the minimum value from the maximum value. Here's how you can do it using the Math.min and Math.max functions:
index.ts234 chars8 lines
In the code above, we first define an array arr
containing some numbers. Then we use the spread operator (...
) to pass all the elements of the array to the Math.min and Math.max functions separately, which returns us their minimum and maximum values respectively. Finally, we subtract the minimum value from the maximum value to get the range of the array.
Note that this approach assumes that the input array is non-empty. If the input array is empty, the Math.min and Math.max functions will return Infinity
and -Infinity
respectively, leading to an incorrect range value.
gistlibby LogSnag