![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 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
Advertisements