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

206
Views
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 answers
Answer question

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 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!