user4556747
user4556747

Reputation:

How to select unique values in d3.js from data

I am using the following code to populate my Combobox using d3.js

d3.csv("Results_New.txt", function(data) {
dataset=data;
d3.select("#road").selectAll("option")
.data(data).enter().append("option").text(function(d){return d.roadname;}).attr("value",function(d){return d.roadname;});
});

There are different rows with the same name. The combobox is populating with these duplicate names. For example in multiple rows the name of the road is I-80.But in the combobox I want to see I-80 only once. How can I do that?

Upvotes: 14

Views: 28704

Answers (2)

Drew Levitt
Drew Levitt

Reputation: 61

d3.map is deprecated - the d3 devs now recommend simply using JavaScript's built-in Array.map. (In fact the entire d3-collection module is now deprecated, with similar rationale for d3.set.)

Here's a concise and (I think) elegant way to do this in ES6, using Array.map, Set, and the spread operator ...:

let options = [...new Set(data.map(d => d.roadname))]; 
// optionally add .sort() to the end of that line to sort the unique values
// alphabetically rather than by insertion order

d3.select('#road')
  .selectAll('option')
    .data(options)
  .enter()
    .append('option')
    .text(d => d)
    .attr('value', d => d);

Upvotes: 6

ahmohamed
ahmohamed

Reputation: 2970

Filter your data retaining unique keys only by d3.map

d3.select("#road").selectAll("option")
    .data(d3.map(data, function(d){return d.roadname;}).keys())
    .enter()
    .append("option")
    .text(function(d){return d;})
    .attr("value",function(d){return d;});

Upvotes: 27

Related Questions