Home > other >  display an array of images in random order JavaScript
display an array of images in random order JavaScript

Time:06-27

I want to print a javascript array of images in random order but expect the middle one I want this one g.jpg to stay in it is positions right now all of them are shuffle, how to separate or absolute g.jpg position. I think I need to add a different class name for g.jpg but I don't know how to do it.

 <html>
<head>
    <meta charset='utf-8'>
    <title></title>
 <style>
    .ppl{
        width: 250px;
    }
 </style>
</head>
<body>
    
<div id="root"></div>

    <script type="text/javascript">


const images = [
  'images/1.jpg',
  'images/2.jpg',
  'images/g.jpg',
  'images/3.jpg',
  'images/4.jpg'
]

const root = document.querySelector('#root')

const shuffle = ([...array]) => {
  let currentIndex = array.length
  let temporaryValue
  let randomIndex

  // While there remain elements to shuffle...
  while (currentIndex !== 0) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex)
    currentIndex -= 1

    // And swap it with the current element.
    temporaryValue = array[currentIndex]
    array[currentIndex] = array[randomIndex]
    array[randomIndex] = temporaryValue
  }

  return array
}

const shuffledImages = shuffle(images)

shuffledImages.forEach(src => {
  const image = document.createElement('img')

  image.src = src
  image.alt = src

  image.classList.add('ppl')
  image.classList.add('pos')

  root.appendChild(image)
})


        
        </script>
</body>
</html>

CodePudding user response:

Seems to be an interesting question. Yes, you can do this way. What I would suggest is, shuffle the four random stuff and then append these.

You can try the following logic that scales. The only difficulty here is, the list of array should be an odd number including the g.jpg.

// Made two arrays of variable lengths.
const a1 = [1, 2, 3, 4].map(a => a   ".jpg");
const a2 = [1, 2, 3, 4, 5, 6, 7, 8].map(a => a   ".jpg");

// Check the arrays:
console.log({ a1, a2 });

// Shuffle in Random Order.
a1.sort(() => 0.5 - Math.random());
a2.sort(() => 0.5 - Math.random());

// Check the arrays:
console.log({ a1, a2 });

// Take the first part and second part.
const f1 = a1.slice(0, a1.length / 2);
const f2 = a2.slice(0, a2.length / 2);
const s1 = a1.slice(a1.length / 2);
const s2 = a2.slice(a2.length / 2);

console.log({ f1, f2, s1, s2 });

// Now combine everything:
const r1 = [...f1, "g.jpg", ...s1];
const r2 = [...f2, "g.jpg", ...s2];

console.log({ r1, r2 });

I have added all the comments inside the code. Let me know if that helps?

Once you have sorted the array side of things, render the HTML based on this.

CodePudding user response:

You could exclude the index for shuffling.

const
    shuffle = ([...array], keep = []) => {
        let i = array.length;
            
        while (i) {
            const r = Math.floor(Math.random() * i);
            i--;
            if (keep.includes(i) || keep.includes(r)) continue;
            [array[i], array[r]] = [array[r], array[i]];
        }
        
        return array;
    }

console.log(...shuffle([1, 2, 3, 4, 5], [2]));

  • Related