I have a small problem. I need to get 4 random images out of array of 6 elements but I don't know how to do it. Images should repeat.
let array = ["../media/pawn.png", "../media/rook.png", "../media/knight.png", "../media/bishop.png", "../media/queen.png", "../media/king.png"];
shuffleArray(array);
array.forEach(function(image) {
let img = document.createElement('img');
img.src = image;
img.height = "45";
img.width = "50";
document.getElementById("random").appendChild(img);
});
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
let temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
If image should repeat you can use simple random like that:
const array = [1,2,3,4,5,6];
for(var i = 0; i < 4; i++){
console.log(array[Math.floor(Math.random() * 5)]);
}
As you can see log can show you same image (in my example just a number).
let array = ["../media/pawn.png", "../media/rook.png", "../media/knight.png", "../media/bishop.png", "../media/queen.png", "../media/king.png"];
const images = Array(4).fill(0).map(() => array[~~(Math.random() * array.length)]);
console.log(images);
You can solve this using a small loop
let images = ["../media/pawn.png", "../media/rook.png", "../media/knight.png", "../media/bishop.png", "../media/queen.png", "../media/king.png"];
function shuffleImages () {
let temp = []
while (temp.length < 4) {
temp.push(images[Math.floor((Math.random() * images.length - 1) + 1)])
}
return temp;
}
let array = shuffleImages()
console.log(array)
array.forEach(function(image) {
let img = document.createElement('img');
img.src = image;
img.height = "45";
img.width = "50";
document.getElementById("random").appendChild(img);
});
<div id="random"></div>