Search code examples
javascriptd3.jsordinals

D3.js: getting every unique value in an ordinal scale


I want to get every unique value in an ordinal scale (built from an array of an array). Let's say this is my dataset:

var people = [
  ["Mary", "Mary Smith", "ID00001", 9.99 ],
  ["James", "James Smith", "ID00002", 19.99 ],
  ["Frank", "Frank Black","ID00003", 19.96  ],
  ["Mary","Mary Brown","ID00004", 9.95  ],
  ["Tony", "Tony Stark", "ID00005", 2319.99 ],
  ["Frank", "Frank Howard","ID00006", 219.96  ],
  ["Mary","Mary Brown","ID00004", 339.95  ]
];

and then I build my scale from this data:

var ordScale = d3.scale.ordinal()
               .domain(people.map( function (d) { return d[0]; }))
               .rangeBands([0, 10], 0); 

That is, despite there being six different people, I'll end up with only four names in my domain (as far as I believe!):

  • Mary
  • James
  • Frank
  • Tony

I have two questions about this:

  1. How do I check what's in the ordinal scale in the console.log?
  2. Assuming I am right and there are only four values in the ordinal scale, how do I alphabetise them?

Solution

  • There are basically two things that you could check about a scale -- the domain and the range. It sounds like you're interested in the domain, so you can check that by calling the respective method:

    console.log(ordScale.domain());
    

    Demo here.

    As for your second question, you can simply sort the array before passing it to .domain():

    people.map( function (d) { return d[0]; }).sort();
    

    Demo here.