Picking index randomly from array in JavaScript


The process of randomly selecting an index from an array holds significant importance in various JavaScript applications, as it enables developers to introduce an element of unpredictability and diversity to their code. By incorporating the capability to pick an index randomly, developers can enhance the dynamism and versatility of their applications, resulting in a more engaging user experience. In this article, we will explore the intricacies of selecting an index randomly from an array in JavaScript, unraveling the underlying techniques and lesser-known methods that empower developers to introduce randomness into their array-based operations. Through a comprehensive understanding of these concepts, developers will be equipped with the knowledge necessary to imbue their code with an element of chance, transforming their applications into captivating and unpredictable experiences.

Problem Statement

The predicament involves the need for an efficient algorithm in JavaScript that can randomly extract an index from an array with equal probability for each index. This challenge stems from the lack of built-in methods for this purpose. The main goal of this article is to provide a comprehensive solution by presenting an algorithm that consistently achieves the desired outcome in an optimal manner.

Sample Input −

Consider an array, let arr = [12, 45, 7, 89, 34, 56], where the task is to randomly select an index from this array.

Sample Output −

The desired output is a single index value, randomly chosen from the given array, in this case, say 3, which represents the index of the number 89 in the array.

Approach

In this article, we are going to see a number of different ways to solve the above problem statement in JavaScript −

  • Using Math.random() with Math.floor()

  • Using the Fisher-Yates (Knuth) Shuffle Algorithm

  • Using the Reservoir Sampling Algorithm

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

To haphazardly select an index from an array in JavaScript, employ the functions Math.random() and Math.floor(). Commence by delineating the array of elements. Generate an arbitrary floating-point value ranging from 0 to 1 using Math.random(). Multiply this fortuitous number by the size of the array to acquire a value between 0 and the array's length (excluding the length itself). To transmute the fractional number into an integer index, employ Math.floor(). Lastly, utilize the acquired index to retrieve the corresponding element from the array for subsequent operations or manipulations.

Example

The code defines a function called getRandomIndex that generates a random index within an array. It uses Math.random() and Math.floor() to obtain a random number between 0 and the array length. The function returns this random index. After defining the function, the code creates an array and calls getRandomIndex with the array as an argument, assigning the result to randomIndex. It then accesses the element at randomIndex and assigns it to randomElement. Finally, it logs the random index and element to the console using console.log() and template literals.

function getRandomIndex(array) {
   let randomIndex = Math.floor(Math.random() * array.length);
   return randomIndex;
}
const array=[12, 52, 232, 112, 999, 34, 77, 94, 88];
const randomIndex=getRandomIndex(array);
const randomElement=array[randomIndex];
console.log(`Random Index: ${randomIndex}`);
console.log(`Random Element: ${randomElement}`);

Output

The following is the console output −

Random Index: 0
Random Element: 12

Method 2: Using the Fisher-Yates (Knuth) Shuffle Algorithm

To randomly pick an index from an array in JavaScript using the Fisher-Yates Shuffle Algorithm, first define the array. Then, initialize a variable with the length of the array minus one. Enter a loop until the current index becomes zero. In each iteration, generate a random index between 0 and the current index. Swap the element at the current index with the element at the random index. Decrement the current index and continue the loop until the first index is reached. After the loop, the array is shuffled. To pick a random index from the shuffled array, generate a random index between 0 and the array's length.

Example

The provided code includes a function called "getRandomIndex" that generates a random index within a specified range. It creates an array using "Array.from" and assigns each element with its corresponding index. The function utilizes a while loop to shuffle the array by swapping elements. The shuffled array's first element is returned as the random index. Outside the function, an array is defined, and the "getRandomIndex" function is called to obtain a random index and the corresponding element. The code then prints the random index and element to the console using template literals for a readable output.

function getRandomIndex(n) {
   const array = Array.from({ length: n }, (_, index) => index);
   var currentIndex = array.length;
   var temporaryValue, randomIndex;

   // While there remain elements to shuffle
   while (currentIndex !== 0) {
   
      // Pick a remaining element
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      // Swap with the current element
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
   }

   // Return the first index
   return array[0];
}
const array=[12, 52, 232, 112, 999, 34, 77, 94, 88];
const randomIndex=getRandomIndex(array.length);
const randomElement=array[randomIndex];
console.log(`Random Index: ${randomIndex}`);
console.log(`Random Element: ${randomElement}`);

Output

The following is the console output −

Random Index: 5
Random Element: 34

Method 3: Using the Reservoir Sampling Algorithm

To randomly pick an index from an array in JavaScript using the Reservoir Sampling algorithm, create a function called getRandomIndex. Initialize currentIndex and randomIndex variables. Loop through the array, starting from index 1, and generate a random number between 0 and currentIndex. If the random number is less than 1 / (currentIndex + 1), update randomIndex to the current index. Increment currentIndex in each iteration. After the loop, return randomIndex as the selected index. This algorithm ensures a uniform distribution of selected indices with constant memory usage, even for large arrays.

Example

The code includes a function named "getRandomIndex" that generates a random index within a given range. It achieves this by creating an array of a specified length, mapping each element to its respective index. The function then initializes variables to keep track of the current and random indexes. Within a loop, a random index is generated between 0 and the current index, and elements are shuffled by swapping them using a temporary variable. Once all elements are iterated, the function returns the last selected index. In the remaining code, the "getRandomIndex" function is called with an array length, and the result is stored in "randomIndex." The value at the randomly selected index is retrieved and printed to the console.

function getRandomIndex(n) {
   const array = Array.from({ length: n }, (_, index) => index);
   let currentIndex = 0;
   let randomIndex;

   for (let i = 0; i < array.length; i++) {
      // Generate a random index between 0 and currentIndex (inclusive)
      randomIndex = Math.floor(Math.random() * (currentIndex + 1));

      // Swap elements at randomIndex and currentIndex
      let temp = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temp;

      currentIndex++;
   }

   // Return the last selected index
   return array[currentIndex - 1];
}
const array=[12, 52, 232, 112, 999, 34, 77, 94, 88];
const randomIndex=getRandomIndex(array.length);
const randomElement=array[randomIndex];
console.log(`Random Index: ${randomIndex}`);
console.log(`Random Element: ${randomElement}`);

Output

The following is the console output −

Random Index: 3
Random Element: 112

Conclusion

In denouement, the task of randomly selecting an index from an array in JavaScript can be effectively accomplished through meticulous implementation. Employing a suitable algorithmic approach, such as employing the Fisher-Yates shuffle or utilizing cryptographic functions for generating random indices, can foster a sense of serendipity and unpredictability in the selection process. By embracing these methodologies, developers can infuse an element of whimsy and intrigue into their code, elevating the overall user experience. Thus, by leveraging these seldom-utilized techniques, JavaScript programmers can confidently bestow their arrays with the allure of fortuity, engendering an environment of delightful uncertainty and novelty.

Updated on: 04-Aug-2023

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements