Random Array Sort
Join the Discussion
Related Resources
Arrays are a useful way of storing a number of similar items. Sometimes we want to access the entries in a particular order and so we sort the array into that order. Other times we may want to just access the entries randomly. If you just want one random entry then selecting an entry randomly is fairly straightforward but if you want more than one entry selected randomly you probably don't want the same entry to be selected twice. The solution is to 'sort' the array into random order and then read as many entries as we need from the start of the array.
To 'sort' an array into random order add the following code (into the head section of your page is probably the most appropriate place):
return (Math.round(Math.random())-0.5); }
We can now randomize any array. The following example shows how:
anyArray.sort( randOrd );
document.write('Random : ' + anyArray + '<br />';);

