Last active
August 29, 2015 14:07
-
-
Save carmour24/12a99de4c3e877ba39cd to your computer and use it in GitHub Desktop.
Function to get a specified number of random elements from an array, optionally filtering using a filter function.
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(elementArray, requiredCount, filter) { | |
| var randomElements = []; | |
| while (randomElements.length < requiredCount) { | |
| var randomIndex = Math.floor(Math.random() * elementArray.length); | |
| // If no filter function has been provided or the filter function returns true | |
| // then add the element to the random array. | |
| var element = elementArray[randomIndex]; | |
| if (!filter || (filter && filter(element, randomIndex, elementArray, randomElements))) { | |
| randomElements.push(element); | |
| } | |
| } | |
| return randomElements; | |
| } |
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
| var elements = [1, 2, 3, 4, 5]; | |
| var twoRandomElements = getRandomElements(elements, 2); | |
| var twoRandomElementsFiltered(elements, 2, function (element) { return element != 4; }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment