Skip to content

Instantly share code, notes, and snippets.

@bendc
Created December 21, 2015 11:13
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bendc/5b001e40754022125172 to your computer and use it in GitHub Desktop.
Save bendc/5b001e40754022125172 to your computer and use it in GitHub Desktop.
Randomize arrays
const shuffle = (arr, mixed = [], pool = arr.slice()) => {
const remaining = pool.length;
if (!remaining) return mixed;
const index = Math.floor(Math.random() * remaining);
const el = pool.splice(index, 1).pop();
mixed.push(el);
return shuffle(arr, mixed, pool);
};
@bendc
Copy link
Author

bendc commented Dec 21, 2015

Example:

shuffle(["Ben", "John", "Alex", "Tom"]); // => ["Alex", "Ben", "Tom", "John"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment