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:
- 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.
- In the function copy the array with the dot operator.
- Loop the number of times matching the number of items you need.
- 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;
};
Comments
Post a Comment