How to Quickly Create Randomly Generated Datasets in JavaScript with D3.js


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 Array.map() 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, withArray.map() we can do this quickly.

var familyMembers = ['Jon', 'James', 'Robert', 'Mary'];
familyMembers = familyMembers.map(function(member){
 return member + ' Sadka'; 
});
console.log(familyMembers); // logs ["Jon Sadka", "James Sadka", "Robert Sadka", "Mary Sadka"]

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 http://jonsadka.com/blog/using-reduce-to-create-arrays-and-objects-in-javascript/)

d3.range(10); // returns [0,1,2,3,4,5,6,7,8,9,10]

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:

newData = d3.range(4).map(function(){
 return d3.range(3).map(Math.random);
});

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

Show your support

Clapping shows how much you appreciated Jon Sadka’s story.