Created
March 8, 2023 06:43
-
-
Save rameshbaskar/5af924d67b5e2d6c3f5a042e03b13a59 to your computer and use it in GitHub Desktop.
Get random items from array
This file contains hidden or 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 getRandomItemsFromArray(sourceArray, numOfItems) { | |
if (numOfItems > sourceArray.length) { | |
throw new Error('Trying to get more items than the array length!!!'); | |
} | |
const shuffledArray = sourceArray.concat().sort((() => Math.random() - 0.5); | |
return shuffledArray.slice(0, (numOfItems - 1)); | |
} | |
// The concat() function returns a copy of the sourceArray so that the original array is not modified. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment