jQuery: ottenere valori casuali da un array

jQuery: ottenere valori casuali da un array

In jQuery è semplice ottenere valori casuali da un array.

La soluzione è la seguente:


(function( $ ) {
  $.getRandomFromArray = function( arr, single ) {
  
   single = single || false; // Se vogliamo un solo valore o tutti
   var total = arr.length - 1;
   var output;
  
   function getRandomInt( min, max ) {
     return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
   }
   
   if( !single ) {
     output = arr.sort(function() {
       return 0.5 - Math.random();
     });
   } else {
     var index = getRandomInt( 0, total );
     output = arr[index];
   }
   
   return output;
   
  };
})( jQuery );

Torna su