1. Computing
Send to a Friend via Email

Random Array Sort

Join the Discussion

Questions? Comments?

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.

One way to 'sort' an array into random order add the following code (into the head section of your page is probably the most appropriate place):

function randOrd(){
return (Math.round(Math.random())-0.5); }

We can now randomize any array. The following example shows how:

anyArray = new Array('3','a','5','F','x','47');
anyArray.sort( randOrd );
document.write('Random : ' + anyArray + '<br />';);

Note that this solution does not perform a completely randon sort on the array and entries will still be biased towards their original positions in the array. This is because of the particular sort algorithm that JavaScript uses.

©2014 About.com. All rights reserved.