Pwdr
Pwdr

Reputation: 3781

How to create exclusive list of CSV entries in D3.js?

I have a CSV file which looks like this:

Category,Value
category1,162
category1,151
category2,124
category1,135
category2,315

I would like to create an exclusive unordered list of the categories (no duplicates of the categories), so the list should look like this:

<ul>
  <li>category1</li>
  <li>category2</li>
</ul>

The array is quite big, so it should be fast. This is what I have so far (displaying some part of the CSV as scatterplot):

  d3.csv("data.csv", function(error, data) {
    data.forEach(function(d) {
    d.Value = +d.Value;
  });

svg.selectAll(".dot")
  .data(data)
  .enter().append("circle")
  .attr("class", "dot")
  .attr("r", 1)
  .attr("cx", function(d) { return x(d.Value); })
  .attr("cy", 10);

What’s the best way to create the category list besides the svg?

Upvotes: 0

Views: 364

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109242

You can simply build another array with the categories:

var categories = [];
data.forEach(function(d) {
  d.Category = Category;
  d.Value = +Value;
  if(categories.indexOf(d.Category) == -1) categories.push(d.Category);
});

// etc

d3.select("body").append("ul").selectAll("li")
  .data(categories)
  .enter().append("li")
  .html(function(d) { return d; });

Upvotes: 2

Related Questions