Skip to content

Instantly share code, notes, and snippets.

@Alex1990
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save Alex1990/f181d458e473ddf6d135 to your computer and use it in GitHub Desktop.

Select an option

Save Alex1990/f181d458e473ddf6d135 to your computer and use it in GitHub Desktop.
Pick N elements from an array randomly.
/**
* Pick N elements from an array randomly.
*/
function randPick(arr, n) {
var len = arr.length;
var randIdx;
var tmp;
while (n--) {
randIdx = Math.floor(Math.random() * len);
tmp = arr[len - 1];
arr[len - 1] = arr[randIdx];
arr[randIdx] = tmp;
len--;
}
return arr.slice(len - arr.length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment