JavaScript Code for Randomly Select Items from An Array Without Repetition

Here is one way to select items from an array without repeting selecting the same item. Selecting items from an array with repetition should be very easy. Just keep randomly generate an array index with Math.floor(Math.random()*array.length).

Logic

Here is the logic behind array item selectoin without repetion:
  1. Define a function that takes 2 parameters. One is the number if items you need from an array, the oither is the original array where you want to pick items from.
  2. In the function copy the array with the dot operator.
  3. Loop the number of times matching the number of items you need.
  4. Once an item is picked, use the array.splice() method to delete that item. This is where the 2nd step is important because the original input array would be modified otherwise.

Code

function selectFromArrayWithoutRepetition(numberOfItems,array){
	var originalArray = [...array];
        var l;
        var arrayWithSelectedItems = [];
         for(let i=0; i<numberOfItems; i++){
		l = originalArray.length;
		var index = Math.floor(Math.random()*l);
		arrayWithSelectedItems.push(originalArray[index]);
		originalArray.splice(index,1);			
	};
	return arrayWithSelectedItems;
};	

Plyaground

Iuput at least 5 items seperated by commas in the box below.

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser