Create dataset from array of numbers using d3.js

I have a simple array with sums for each category of things. Simplified version:

var quantities = [{"type": "apple","number": 51}, 
{"type": "orange","number": 19}, 
{"type": "lemon","number": 11}];

      

From this data I'm going to draw one circle for each item, i.e. 51 circles with type = apple, 19 for orange, 11 for lemon. I would like to create an array based on this data, with one entry for each object -

dataset = [{apple},{apple},{apple}...]

      

What would be the best way to create this dataset in d3? I've tried the datamap functions with no luck. Or is there a better way to draw the correct amount of each category based on my original array without a dataset step? Thank!

+3


source to share


1 answer


You can use some maps and flatten them to convert to one line:

var quantities = [{"type": "apple","number": 51}, 
{"type": "orange","number": 19}, 
{"type": "lemon","number": 11}];

var joined = quantities.map(function(x) {
  return Array.apply(null, new Array(x.number)).map(function (y) {
    return x.type; }); }).reduce(function(prev, z) {
      return prev.concat(z); }, []) 

console.log(joined);

      



In case you're wondering what this is Array.apply(null, new Array(x.number))

... it's an idiom to create an initialized array from an uninitialized array of a specified length, for the reason that the former is displayable and the latter is not.

+3


source







All Articles