How to select a random element from array in JavaScript ?


When working with arrays in JavaScript, cases often require selecting a random element from an array. In Javascript we can use various inbuilt methods like Math.random() with Math.floor(), using the Math.random() Method with a Helper Function, and Using the Array.prototype.sort() Method to select a random element from an array. In this article we will explore all these methods and explain them with the help of examples.

Method 1:Using Math.random() with Math.floor()

This method uses the combination of Math.random() and Math.floor() to generate a random index within the range of the array's length.

Syntax

array[Math.floor(Math.random() * array.length)];

Here, the Math.random(), returns a random number between 0 (inclusive) and 1 (exclusive). Multiplying this value by the array's length ensures the index falls within the appropriate range. Math.floor() is used to round down the generated index to the nearest integer.

Example

In the below example, the random index is generated using Math.random() * array.length, which yields a decimal value between 0 (inclusive) and the array's length (exclusive). The Math.floor() function rounds down this decimal value to the nearest integer, ensuring that it falls within the valid index range. Finally, array[randomIndex] retrieves the element at the randomly generated index.

const array = [1, 2, 3, 4, 5];
const randomElement = array[Math.floor(Math.random() * array.length)];
console.log(randomElement);

Output

4

Method 2:Using the Math.random() Method with a Helper Function

This method involves encapsulating the random element selection logic within a helper function. By passing an array as a parameter to the function, a random index is generated using Math.random() and Math.floor(),which allows easy retrieval of elements.

Syntax

Math.random()

Here, the Math.random() method does not require any parameters. When called, it returns a random floating−point number between 0 (inclusive) and 1 (exclusive).

Example

In the below example code, the getRandomElement() function is defined to take an array as its parameter. The function implements the random element selection logic explained in Method 1. By calling getRandomElement(array), we can retrieve a random element from the given array.

function getRandomElement(array) {
    return array[Math.floor(Math.random() * array.length)];
  }
const array = ["apple", "banana", "orange", "grape"];
const randomElement = getRandomElement(array);
console.log(randomElement);

Output

banana

Method 3:Using the Array.prototype.sort() Method

In this method, the Array.prototype.sort() method is utilized to shuffle the array randomly. By subtracting a randomly generated value between 0 and 0.5 from 0.5, the elements are sorted in a random order. The first element from the shuffled array represents the randomly selected element from the original array.

Syntax

array.sort(compareFunction)

Here, array is the array on which the sort() method is called, and compareFunction (optional) is the callback function used to determine the order of the elements. The compareFunction is optional. If provided, it specifies the logic for comparing elements in the array. It should return a negative value if the first element should be placed before the second element, a positive value if the first element should be placed after the second element, or zero if both elements are considered equal.

Example

In the below example, the array.sort() method is called with a comparator function that subtracts a random value between 0 and 0.5 from 0.5. This causes the array's elements to be sorted randomly. Finally, [0] retrieves the first element from the shuffled array, representing a random element from the original array.

const array = [10, 20, 30, 40, 50];
const randomElement = array.sort(() => 0.5 − Math.random())[0];
console.log(randomElement);

Output

40

Conclusion

In this example, we discussed how we can select a random element from an array in javascript using different inbuilt functions. We used Math.random() with Math.floor(), creating a helper function, or utilizing Array.prototype.sort(), each method provides a reliable way to obtain a random element from an array. We can use any of the method depending the requirement of the problem in hand.

Updated on: 18-Jul-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements