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

JavascriptWeb DevelopmentObject Oriented Programming

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

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

Here is the code for doing the same −

Example

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);

The output in console can be −

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
raja
Published on 19-Aug-2020 10:56:06
Advertisements