I want to run a function that each time randomly chooses an element from an array that wasn\'t chosen before. And if all elements were chosen, I want to reset the used eleme
You can try something like this:
data
and put it in chosenItems
data
reaches 0
, set chosenItems
or originalArray
as data and repeat process.Benefit of this approach would be,
function randomize(arr) {
let data = [...arr];
let chosenItems = [];
function getRandomValue() {
if (data.length === 0) {
data = chosenItems;
chosenItems = [];
}
const index = Math.floor(Math.random() * data.length);
const choice = data.splice(index, 1)[0];
chosenItems.push(choice);
return choice;
}
return {
randomItem: getRandomValue
}
}
const dummyData = [ 1,2,3,4,5 ];
const randomizeData = randomize(dummyData);
for (let i = 0; i< 10; i++) {
console.log(randomizeData.randomItem())
}