JavaScript remove random item from array and then remove it from array until array is empty

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 returned as the first element of the returned array:

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]); // Using spread to preserve original array
Leicester City
Fulham
Everton
Chelsea
Manchester City
Liverpool
Cardiff City
Arsenal
Manchester United

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

Time Complexity: O(n²) - Each splice operation shifts remaining elements

Space Complexity: O(1) - Only using constant extra space

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. The Fisher-Yates (or Knuth) shuffle ensures a uniform random distribution of elements.

How It Works

The Fisher-Yates algorithm works by iterating from the last element to the first, swapping each element with a randomly chosen element from the remaining unshuffled portion. After shuffling, we can simply pop elements from the end.

Example

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

    // Remove items from the end until empty
    while (shuffledArray.length > 0) {
        const removedItem = shuffledArray.pop();
        console.log(`Removed: ${removedItem}, Remaining: [${shuffledArray.join(', ')}]`);
    }
    console.log("Array is now empty");
}

// Example usage
const myArray = [1, 2, 3, 4, 5];
removeRandomItemsWithShuffle(myArray);
Removed: 4, Remaining: [1, 3, 2, 5]
Removed: 5, Remaining: [1, 3, 2]
Removed: 2, Remaining: [1, 3]
Removed: 3, Remaining: [1]
Removed: 1, Remaining: []
Array is now empty

Time Complexity: O(n) - Linear time for both shuffle and removal

Space Complexity: O(1) - Constant extra space (excluding the copy)

Comparison

Method Time Complexity Space Complexity Best For
Splice Method O(n²) O(1) Small arrays, simple implementation
Fisher-Yates Shuffle O(n) O(1) Large arrays, performance-critical applications

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: 2026-03-15T23:18:59+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements