find the range of all elements in an array in javascript

To find the range of all elements in an array in JavaScript, we can use the spread operator to expand the array, then use the Math.min and Math.max methods to find the smallest and largest values in the array, respectively. We can then subtract the smallest value from the largest value to get the range.

Here's an example code snippet:

index.tsx
const arr = [1, 5, 3, 8, 2, 9, 4];

const [min, max] = [Math.min(...arr), Math.max(...arr)];
const range = max - min;

console.log(range); // Output: 8
152 chars
7 lines

In the above code, we first create an array arr that contains some numbers. We then use destructuring to assign the smallest and largest values in arr to the variables min and max, respectively. Finally, we subtract min from max to get the range of all elements in arr.

gistlibby LogSnag