As you may be aware, my current task involves assigning random positions from a list to various div elements. The code I am using to achieve this is as follows:
var list = [100,210,320,430];
var square1 = document.getElementById("square1")
var square2 = document.getElementById("square2")
var square3 = document.getElementById("square3")
var square4 = document.getElementById("square4")
var squares = [square1,square2,square3,square4]
for(let looprun = 0; looprun<4; looprun++){
r=Math.floor(Math.random()*list.length)
console.log(looprun)
squares[looprun].style.left = (list[r])+"px";
list.splice(r)
if(looprun === 3){
console.log("End of Loop Reached")
}
}
While everything is functioning correctly, there is one issue that needs addressing: due to the random nature of the selection process, there are instances where div elements end up with the same position, resulting in overlap.
For instance, in the image below, you can see that the fourth div has overlapped with the third, as described above.
Attempts to prevent duplicate selections using list.splice
have not been successful, as some div elements remain unpositioned. I am seeking assistance in resolving this issue to ensure that the same value from the list is not chosen multiple times. Any guidance would be greatly appreciated.