Skip to content

Instantly share code, notes, and snippets.

@knightazura
Last active January 11, 2021 03:17
Show Gist options
  • Save knightazura/e5d2b7b0652fc9f9d9d42a0151c46ffb to your computer and use it in GitHub Desktop.
Save knightazura/e5d2b7b0652fc9f9d9d42a0151c46ffb to your computer and use it in GitHub Desktop.
Pick random element(s) from an array by given number
function randomPick(source = [], anyNumber = 1) {
if (source.length > 0) {
let result = [];
// Duplicate original array
let poppedArray = [].concat(source);
let currentLength = poppedArray.length;
for (let i = 0; i < anyNumber; i++) {
// Generate random number to pick an element inside array
const magicNumber = Math.floor(Math.random() * (currentLength - Math.random()));
// Slice the array so picked element won't be picked anymore
result.push(poppedArray.splice(magicNumber, 1)[0]);
currentLength = poppedArray.length;
}
return result;
}
return source;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment