Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

207
Vistas
Shuffle Array and Display with Button With No Repeats

Say I had the following array: [x, y, z]

If I wanted to shuffle that array and display each element one by one (without repeating) on each button click, how would I write that function with Javascript to populate the paragraph? Also, would you recommend writing the code inline or on a separate sheet and then imbedding it? Thank you in advance.

<!doctype html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title> Title </title>
</head>

<body>
    <script src="javascript.js"></script>
    <div> 
        <p></p>
    </div>
    <div>
    <button onclick="displayElement()">Start</button>
    </div>
    
</body>

</html>
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You need a shuffling function (I got one) and some structure around it for the button click that will reveal the shuffle.

var arr = ['x', 'y', 'z']
var button = document.querySelector(".my-button");
var reset = document.querySelector(".my-reset");
var shuffled = shuffle(arr)
var index = 0;

button.addEventListener('click', function() {
  if (index < shuffled.length) {
    console.log(shuffled[index]);
    index++
  }
})

reset.addEventListener('click', function() {
  shuffled = shuffle(arr)
  index = 0;
})



function shuffle(str_or_arr) {
  var a = typeof str_or_arr == 'string' ? str_or_arr.split('') : str_or_arr
  var n = a.length;
  for (var i = n - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;
  }
  return typeof str_or_arr == 'string' ? a.join('') : a;
}
<button class="my-button">next</button>
<button class="my-reset">reset</button>

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda