how to quickly create randomly generated datasets in javascript with d3

Often times in javascript and D3, we want to quickly create randomly-generated, “fake” data on the fly for testing and iterative development.  To help speed things up, we can combine the d3.range() operator and the native prototype to make up large data sets instantly.

javascript map explained

The .map() Array prototype is a function that takes in a callback as the argument and invokes the function on each item in the array.

Suppose we had an array of first names in a family ['Jon','James','Robert','Mary'] and we wanted to give them all the same last name, with we can do this quickly.

d3 range explained

D3 has availed a d3.range() function, which creates a numerical array given a specified range (start value and end value) and step size (similar to the blog post I wrote about here

Note the above is equivalent to d3.range(0,10,1). If only one argument is provided, D3 defaults to a start value of 0 and a step size of 1.

create data

Now we can method chain the two functions to generate a data collection with desired arrays and values.  For example, if we wanted to generate a collection of 6 arrays, each with 3 random values, we could write the following script:

The following are three concurrent invocations of the function. As you can see, new random data is generated each invocation.

first call second call third call