Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
How to get 4 random images out of array of 6 images in Javascript

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;
    }
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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).

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!