Last active
January 11, 2021 03:17
-
-
Save knightazura/e5d2b7b0652fc9f9d9d42a0151c46ffb to your computer and use it in GitHub Desktop.
Pick random element(s) from an array by given number
This file contains 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
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