JavaScript array_rand
Return key/keys for random entry/entries in the array
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 | function array_rand ( input, num_req ) { // Return key/keys for random entry/entries in the array // // version: 1008.1718 // discuss at: http://phpjs.org/functions/array_rand // + original by: Waldo Malqui Silva // * example 1: array_rand( ['Kevin'], 1 ); // * returns 1: 0 var indexes = []; var ticks = num_req || 1; var checkDuplicate = function ( input, value ) { var exist = false, index = 0; while ( index < input.length ) { if ( input [ index ] === value ) { exist = true; break; } index++; } return exist; }; if ( input instanceof Array && ticks <= input.length ) { while ( true ) { var rand = Math.floor( ( Math.random( ) * input.length ) ); if ( indexes.length === ticks ) { break; } if ( !checkDuplicate( indexes, rand ) ) { indexes.push( rand ); } } } else { indexes = null; } return ( ( ticks == 1 ) ? indexes.join( ) : indexes ); } |
Examples
Running
1 | array_rand( ['Kevin'], 1 ); |
Should return
1 |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have array_rand goodness in JavaScript.
@pwoul, You are referencing an array/object called "tableau" instead of the one you randomized, "alea". Change it to "alea" (if that's what you want), and the number will vary... best wishes, Brett
Hi, first i'd like to thank you for this very nice function.
But (there's always one :D) i have a problem using it :
var result = "";
var alea = array_rand(["a","b","c","d","e","f","g","h"], 8);
for(var i in alea)
{
result = result + tableau[i];
}
This code always returns the string "abcdefgh", the order of the characters isn't random :/
Thanks for your help :)


pwoul
10 May '09
(here's the code if someone needs it)
var result = ""; alea = array_rand(["a","b","c","d","e","f","g","h"], 8); for(var i in alea) { var kikoo = alea[i]; result = result + tableau[kikoo]; }