Last active
August 29, 2015 13:56
-
-
Save jawinn/9299438 to your computer and use it in GitHub Desktop.
Multiple *Unique* Array Values (uses jQuery)
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
| // MULTIPLE *UNIQUE* ARRAY VALUES (uses jQuery) | |
| // Parameter arr: array containing values | |
| // Parameter totalNum: total number of values to get | |
| // Returns Array | |
| function rndArrValues(arr, totalNum){ | |
| if ( totalNum <= 0 ){ return; } | |
| var theResult = []; | |
| var newElement; | |
| // if array same size or equal, return whole array | |
| if ( arr.length <= totalNum ){ | |
| return arr; | |
| } | |
| else { | |
| // loop through array until we have as many values as we need | |
| while ( theResult.length < totalNum ) | |
| { | |
| newElement = arr[ Math.floor(Math.random() * arr.length) ]; | |
| // value isn't already in our array | |
| if ( $.inArray(newElement, theResult) == -1 ) { | |
| theResult.push( newElement ); | |
| } | |
| } | |
| } | |
| return theResult; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment