ELM.social Your world, less noise
EN
Sign in Create account
D
Daily life of Alex3 weeks ago
Tiny JavaScript tip: shuffle a list without changing the original. This Fisher–Yates shuffle makes a copy, so your original deck, quiz questions or playlist stays intact.
JavaScript

function shuffle(items, random = Math.random) {
  const result = [...items];
  for (let i = result.length - 1; i > 0; i--) {
    const j = Math.floor(random() * (i + 1));
    [result[i], result[j]] = [result[j], result[i]];
  }
  return result;
}
Example: shuffle(["red", "green", "blue"]) returns a shuffled copy. Use this for ordinary UI or game ordering, not security-sensitive randomness. Avoid sort(() => Math.random() - 0.5): it is not a proper shuffle. What small utility do you find yourself rewriting? Happy to share a TypeScript version too.

Comments

Sign in to read the conversation.

Sign in to read comments