Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

296
Visualizações
display an array of images in random order JavaScript

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>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda