Open In App

How to Select a Random Element from Array in TypeScript ?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are given an array in TypeScript and we have to select a random element every time the code runs. It will automatically select a new random element every time and return it. The below approaches can be used to accomplish this task:

Using Math.random() function

  • The “Math.random()” function generates a random number every time between 0 and 1.
  • Multiply it with the length of the array to get the numbers between 0 and the length of the array.
  • Use the “Math.floor()” method to get the index ranging from (0 to array.length-1).

Example: The below code implements the above-specified methods to select a random element from a TypeScript array.

Javascript




let arr: number[] =
    [1, 2, 3, 4, 5];
 
if (arr.length === 0) {
    console.log(undefined);
} else {
    const ind: number =
        Math.floor(Math.random() * arr.length);
    const result: number = arr[ind];
    console.log(`Random Element = ${result}`);
}


Output:

Random Element = 3

Using splice() method

  • First the random index is generated by using the random() method.
  • Now, the splice() method removes one element from the array at the randomly generated index. The splice method returns an array containing the removed elements.
  • The array returned will be of size 1 and the element which it contains is indeed the random element.

Example: The below code is practical implementation of splice() method to get the random element from array.

Javascript




let arr: number[] =
    [1, 2, 3, 4, 5, 6, 8, 7];
 
if (arr.length === 0) {
    console.log(undefined);
}
else {
    const ind =
        Math.floor(Math.random() * arr.length);
    const result = arr.splice(ind, 1)[0];
    console.log(`Random Element = ${result}`);
}


Output:

Random Element = 2


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads