Remove Random Item from Array in JavaScript



We are given an array of string/number literals. We are required to create a function removeRandom() that takes in the array, recursively removes one random item from it, and simultaneously prints it until the array contains items.

This can be done by creating a random number using Math.random(), removing the item at that index using Array.prototype.splice(), and printing it until the length of the array shrinks to 0.

Approaches to remove random items from array

Following are the different approaches to removing the random item from an array and then removing it from the array until the array is empty ?

Using Splice Method

The splice method is a powerful function in JavaScript that allows you to modify an array by adding or removing items at a specified index. When you want to remove an item, you can provide the index of the item you want to delete along with the number of items to remove.
Math.random() generates a number between 0 and 1, which we scale to the array's length and floor it to get an integer index.

const randomIndex = Math.floor(Math.random() * array.length);
The splice method removes the item at the chosen index. The removed item is logged for visibility.
const removedItem = array.splice(randomIndex, 1)[0];

The while loop continues until the array's length reaches 0.

while (array.length > 0) { }

Example

Here is the code for doing the same ?

const arr = ['Arsenal', 'Manchester United', 'Chelsea', 'Liverpool',
'Leicester City', 'Manchester City', 'Everton', 'Fulham', 'Cardiff City'];
const removeRandom = (array) => {
   while(array.length){
      const random = Math.floor(Math.random() * array.length);
      const el = array.splice(random, 1)[0];
      console.log(el);
   }
};
removeRandom(arr);

Note ? As it is a random output, it is likely to differ every time, so this is just one of many possible outputs.

Output

Leicester City
Fulham
Everton
Chelsea
Manchester City
Liverpool
Cardiff City
Arsenal
Manchester United

Time complexity: O(n²)

Space complexity: O(1)

Using Fisher-Yates Shuffle

A more efficient method for removing items from an array involves shuffling the array first and then popping items from it. This technique is advantageous as it eliminates the need to use the splice method multiple times, thus streamlining the process. Popular algorithms for shuffling include the Fisher-Yates (or Knuth) shuffle, which ensures a uniform random distribution of elements.

Example

function removeRandomItemsWithShuffle(array) {
    // Shuffle the array using Fisher-Yates Algorithm
    for (let i = array.length - 1; i > 0; i--) {
        const randomIndex = Math.floor(Math.random() * (i + 1));
        [array[i], array[randomIndex]] = [array[randomIndex], array[i]];
    }

    // Remove items from the end until empty
    while (array.length > 0) {
        const removedItem = array.pop();
        console.log(`Removed Item: ${removedItem}`);
        console.log(`Remaining Array: ${array}`);
    }
    console.log("The array is now empty.");
}

// Example usage
const myArray = [1, 2, 3, 4, 5];
removeRandomItemsWithShuffle(myArray);

Output

Removed Item: 4
Remaining Array: [1, 3, 2, 5]
Removed Item: 5
Remaining Array: [1, 3, 2]
Removed Item: 2
Remaining Array: [1, 3]
Removed Item: 3
Remaining Array: [1]
Removed Item: 1
Remaining Array: []
The array is now empty.

Time Complexity: O(n)

Space Complexity: O(1)

Conclusion

The splice-based approach is simple and intuitive but less efficient for large arrays due to its O(n²) time complexity. The Fisher-Yates shuffle is the better option for performance-critical applications, ensuring an efficient O(n) solution for removing random items until the array is empty.
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2024-12-13T13:53:44+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements