find the range of all elements in an array in typescript

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.ts
const arr: number[] = [1, 5, 3, 6, 2, 7, 9];

const minVal = Math.min(...arr);
const maxVal = Math.max(...arr);

const range = maxVal - minVal;
console.log(`The range of the array is ${range}`); // output: The range of the array is 8
234 chars
8 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.

related categories

gistlibby LogSnag