Last active
January 23, 2019 08:57
-
-
Save Kobe/5b5afbceaec8a1d6e5630072fa709aaa to your computer and use it in GitHub Desktop.
shuffle JS array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>shuffle lunch</title> | |
</head> | |
<body> | |
<h1>lunch people</h1> | |
<div id="lunch"></div> | |
<button name="lunch">Shuffle</button> | |
<h2>all people</h2> | |
<div id="people"></div> | |
<script> | |
// show people list | |
const people = [ | |
"person 1", | |
"person 2", | |
"person 3", | |
"person 4", | |
"person 5", | |
"person 6", | |
"person 7", | |
"person 8", | |
"person 9", | |
"person 10" | |
]; | |
document.getElementById("people").innerHTML = people.join(", "); | |
// shuffle people on click | |
document.querySelector("button[name='lunch']").addEventListener("click", () => { | |
const people = document.getElementById("people").innerHTML.split(', '); | |
for (let i = people.length - 1; i > 0; i--) { | |
const j = Math.floor(Math.random() * (i + 1)); | |
[people[i], people[j]] = [people[j], people[i]]; | |
} | |
document.getElementById("lunch").innerHTML = people.slice(0,3).join(", "); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment