How to avoid duplication photo while displaying random photos each time?
let photosList = [
'./images/1.jpg',
'./images/2.jpg',
'./images/3.jpg',
'./images/4.jpg',
'./images/5.jpg',
'./images/6.jpg'
];
function RandomIndex() {
return Math.floor(Math.random() * photosList.length);
}
function showList() {
document.querySelectorAll('.classImg').forEach(function(tag) {
let index = RandomIndex();
tag.src = photosList[index];
})
}
showList();
You can do something like this:
let photosList = [
'./images/1.jpg',
'./images/2.jpg',
'./images/3.jpg',
'./images/4.jpg',
'./images/5.jpg',
'./images/6.jpg'
];
let photoSelected = new Array(photosList.length).fill(false);
function RandomIndex() {
return Math.floor(Math.random() * photosList.length);
}
function showList() {
document.querySelectorAll('.classImg').forEach(function(tag) {
let index = RandomIndex();
while(photoSelected[index] == true){
index = RandomIndex();
};
photoSelected[index] = true;
tag.src = photosList[index];
})
}
showList();
Hope, it helps!!