get a random element from an array in typescript

To get a random element from an array in TypeScript, you can make use of the Math.random() function and the bracket notation to access a random index of the array.

Here's an example code snippet:

index.ts
const myArray: string[] = ["apple", "banana", "orange", "pear"];

const randomIndex = Math.floor(Math.random() * myArray.length);
const randomElement = myArray[randomIndex];

console.log(randomElement);
203 chars
7 lines

In this example, we first define an array of strings called myArray.

We then generate a random index by multiplying a random decimal between 0 and 1 (generated by Math.random()) with the length of the array, and then rounding down to the nearest integer using Math.floor().

Finally, we access the element of the array at that randomly generated index with myArray[randomIndex].

This will give us a random element from the array, which we then log to the console.

Note: The above code assumes that the array is non-empty. If the array is empty, myArray.length will be 0, and Math.random() multiplied by 0 will always equal 0, so randomIndex will always be 0. It's good practice to check that the array is not empty before attempting to get a random element from it.

gistlibby LogSnag