Skip to content

Instantly share code, notes, and snippets.

@jawinn
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save jawinn/9299438 to your computer and use it in GitHub Desktop.

Select an option

Save jawinn/9299438 to your computer and use it in GitHub Desktop.
Multiple *Unique* Array Values (uses jQuery)
// 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