# Cures for the Common Ailments ' Getting a Random Item in JavaScript

At the end of the day yesterday one of my peers at my client came over and asked me how to randomly select an item from a SharePoint List. She was retrieving the list using jQuery and only wanted to display one item from the list, but she wanted that item to be random each time the page was loaded. She felt it would ultimately be the simplest solution to do this on the client, and I agreed. Our problem really came down to our personal limits using JavaScript, neither of us had done anything with random yet. I knew there had to be some pseudo-random number generator available, I have not met a modern language that does not have something to offer random yet.

Turns out JavaScript does have a random function that is a member of the Math object. I looked at a few uses of this function and decided using it with Math.floor() would produce the result we were after.

First, Math.random produces a 'random' value between 0 and 1. But we needed to randomly select an array item, which would be an integer index between 0 and the length '1. So multiplying the random result by the array's length will almost produce the index value desired. Passing the value to the Math.floor method will round the result down to the closest integer value. Now we have a 'random' integer value that can be reliably used to select an item from the array of items. The following code is an example of how to test this methodology:

<script type="text/javascript"

charset="utf-8"

>

$(document).ready(function

() {

var

temp = ['1'

,'2'

,'3'

,'4'

,'5'

,'6'

];

$("#container"

).html((temp[get_random(temp.length)]));

});

function

get_random(max) {

if

(undefined === max) {

max = 5;

}

var

ranNum = Math.floor(Math.random() * max);

return

ranNum;

}

</script>