score:4

Accepted answer

To explain the original code:

var nodes = d3.range(200).map(function() { 
                                  return {radius: Math.random() * 12 + 4}; 
                             });

It starts with d3.range(200). That function creates an array of integers from 0 to 199. Then that array's .map( callbackFunction ) method is called. The map function creates a new array of the same length as the array that calls it, but each element of the new array is the value returned from the callback function. The callback function is given the value from the array and its index as parameters, but those aren't used here. Instead, the integers are ignored and a new object is returned, containing a single property, radius, set to a random number between 4 and 16.

Another way to do the same thing (using a syntax that might be more familiar if you have experience with other programming languages) would be:

var nodes = new Array(200);
for(var i=0; i<200; i++) {
    nodes[i] = {radius: (Math.random() * 12 + 4)};
}

Either way, the end result is just a 200-element array of objects with random radius values.

This is all unrelated to the d3.map object, which is a formal implementation of a hashmap data structure, for use if there is a possibility that your data keys will conflict with internal Javascript Object properties and function names.

Now, as to what you are trying to do. The d3.csv function reads your file and creates an array of named objects. That array is passed as the parameter to your callback function. If you want to create a new array of objects, each one of which is based on a separate data row from your csv file, then you could call the array mapping function on your csv array directly:

d3.csv("fuel.csv", function(csv) {

/* This doesn't do anything.  
// You're parsing the strings but not saving the result!
for (var i = 0; i < csv.length; i++) {
                parseFloat(csv[i].comb),
}
*/

var nodesFuel = csv.map(function(d) { 
                      return {radius: parseFloat(d.comb) };
                    });

/* or if you want to save the parsed value in the original array:
var nodesFuel = csv.map(function(d) { 
                      d.comb = parseFloat(d.comb);
                      return {radius: d.comb };
                    });
*/

The array nodesFuel is now an array the same length as csv, with each entry an object containing the property radius, where the radius value is the parsed value of the comb property from the corresponding entry in the csv array.


Related Query

More Query from same tag