This article covers how to select a random item from an array in JavaScript. It also contains an example of how to test and visualize the results using the command line or the browser.

Step 1. Create a project

To get started, create a new project. On a Mac I would do it like this

$ mkdir -p ~/projects
$ cd ~/projects
$ mkdir js-rolldice-101
$ cd js-rolldice-101

Step 2. Initialize the project as a module

To use a more up to date version of JavaScript, we need to use npm to indicate that our code is a module. If that is new to you, see the link to my article on creating a JavaScript module at the end of this article.

  • Run this command to create a package.json file in the root of your project:
$ npm init -y 
  • Open the project in a code editor
  • Add this line to package.json under the description and save the file:
"type": "module",

Step 3. Create a JavaScript file

Use the editor to create a new file called rolldice.js or on the Mac command line:

$ touch rolldice.js

Step 4. Create the rollDice function

Edit rolldice.js and add the following:

The code does the following:

  • Exports a rollDice function that takes an array (list) as an argument and returns a random item from the array
  • Math.random() returns a random number between 0.0 and less than 1.0
  • Multiplying the random number times list.length returns a value 0 and a fraction to the length of the array (list.length) - 1 and a fraction
  • The Math.floor function will round the value down
  • For example: if you have an array length of 3, the possible values will be 0, 1 or 2
  • The calculated value will be used as a zero-based index to return a random item from the array

Step 5. Add a test file

To test the function you can create a special test module that calls the rollDice function x number of times. It should contain a test function that logs the result and gives you an estimate of how evenly distributed the results are.

In the example below I will show you how to use the JavaScript reduce method to count the occurrences of each item in the source array that ends up in the results.

Based on the results you can infer the approximate distribution of each item in the array. If the function is working properly you should have a somewhat even, if not exactly even distribution of each item across the results.

In other words if you have an array of A, B, C, D, E and you ran the function 100 times you would ideally get a result where each item appeared 20 times. Since the results are random, it would be very rare if you ever saw that exact distribution. But you would hope for something close to it. At the very least you would want to make sure that each item in the source array appears at least once in the results.

  • Create a new file called test-rolldice.js
  • Paste in this code and save the file:

The code does the following:

  • imports the rollDice function
  • defines a function to test the rollDice function
  • defines the source array to be used for testing
  • defines a constant limit for generating an array of roll dice results (rolls)
  • generates a random array of dice roll results against the source array
  • logs the array of dice rolls results
  • uses the JavaScript reduce method to count the occurrences of each item in the results array
  • logs the summary of the occurrences
  • calls the test function

Step 6. Run the test function

To run the test function do the following from the projects folder:

node test-rolldice.js

You should see a result similar to this:

[
  'B', 'D', 'A', 'B', 'C', 'E', 'C', 'A', 'B', 'A', 'E',
  'B', 'E', 'E', 'C', 'A', 'C', 'B', 'A', 'B', 'E', 'B',
  'D', 'C', 'B', 'B', 'B', 'C', 'B', 'C', 'D', 'B', 'D',
  'E', 'B', 'B', 'E', 'E', 'A', 'D', 'B', 'A', 'B', 'D',
  'B', 'B', 'A', 'A', 'B', 'B', 'C', 'B', 'B', 'B', 'B',
  'B', 'C', 'C', 'C', 'A', 'B', 'E', 'A', 'B', 'E', 'C',
  'B', 'D', 'D', 'C', 'C', 'D', 'C', 'C', 'B', 'A', 'B',
  'C', 'E', 'D', 'E', 'C', 'E', 'E', 'B', 'E', 'D', 'B',
  'C', 'C', 'D', 'E', 'B', 'E', 'B', 'A', 'E', 'C', 'A',
  'C'
]
{ B: 34, D: 12, A: 14, C: 22, E: 18 }
  • all but the last line is the array of results
  • the last line is the summary of the occurrences
  • if you run it several times the summary may never show an exact 20 (1/5 of the array) for all items
  • but most runs should result in a somewhat balanced distribution

Step 7. Run the test in a browser

To better visualize the results, I'm now going to show you how to map them to a grid in a browser using a canvas element and a few simple drawing commands.

  • Create a file called index.html in the root of your project
  • Paste in this code and save it:

The code does the following:

  • defines a header section
  • defines a title to appear in the browser tab
  • loads a stylesheet (app.css) that will need to be created
  • defines a body section
  • defines a canvas element where we will draw a grid to visualize a series of calls to the function
  • loads a script module (app.js) that will need to be created

Step 8. Create a stylesheet

To keep things neat and simple you can use a stylesheet to draw the canvas in the middle of the screen.

  • In the root of the project create a file called app.css
  • Paste in the code below and save the file:

The code does the following:

  • centers the canvas element in the middle of the screen

Step 9. Create the app file

In this step you define a JavaScript module to be loaded and run by the index.html file every time the page loads. The module will initialize a set of 100 rollDice results using a source array of color values. The results should be converted to a 10 x 10 grid for easy display.

If the code is working correctly you should see a somewhat even distribution of the colors in the source array across the grid.

  • In the root of the project create a file called app.js
  • Paste in the code below and save the file:

The code does the following:

  • gets a handle to the canvas element in the HTML
  • defines a series of constants
  • to simplify the code a square will be drawn where width and height are the same constants
  • SCREEN_SIZE is the width and height of the canvas element (it should match the canvas width and height attributes)
  • DIM is the row and columns of the grid to represent each result which will be show in a grid "cell"
  • CELL_SIZE calculates the size of a cell to draw on the screen by dividing the screen size by the number of rows or columns
  • BORDER is the border size to leave empty around each cell
  • NEON_PINK is a constant value for a neon color option to choose from
  • SOURCE is an array of random colors to choose from
  • an array of random rolls is filled with results
  • the length of the array is DIM * DIM, the number of results to fill a DIM * DIM grid (10 x 10 cells = 100 results needed)
  • the arr (array) result is logged to the console which you can view in the browser via the debugger / inspector console window
  • a context handle to the canvas object is created for drawing
  • the context is cleared and replaced with a background color
  • a cursor for looping through the array is created
  • inner and outer loops for converting the array to a grid are defined
  • the color in the result array at the current cursor position is used to define the fill color for the current cell
  • adjustments are made to draw the cell slightly smaller so it appears to have a border around it

Step 10. Test the project in the Chrome browser

You have to run the code through a local Web server.

On a Mac you can serve the files from the current folder using this command:

python -m SimpleHTTPServer $PORT || 8000
  • Leave that command running
  • Open up the Chrome browser and browse to:
http://localhost:8000/

To see different results, reload the browser window.

Conclusion

In this article you learned how to:

  • generate a function that returns a random item from an array
  • write a test function to see how evenly distributed the results were
  • use the canvas object in a browser to visualize the results

Source Code

Related Articles

References

  • Math.random() - [1]