user4556747
user4556747

Reputation:

Want to show unique values only using d3.js not working

I have large dataset with the same detector having multiple occurrence. There are also many detectors. I want to fill a combobox with the unique detectors only. I am using the following code:

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

But its not showing unique detector codes. Rather the combobox is being filled with number from 1 to ongoing. How can I do my desired goal. My sample simple dataset is

var data=[{"code":5222,"date":3-4-2015},{"code":5222,"date":3-6-2015},{"code":5222,"date":3-7-2015},];

The data has in real a large number of detectors with unique code. I want to show these unique codes in the combobox. For the above case there will be only one 5222 in the options

Upvotes: 0

Views: 4261

Answers (2)

Cassiopea
Cassiopea

Reputation: 275

You could solve this problem using d3.set() method: https://github.com/d3/d3-collection/blob/master/README.md#sets.

The code will be:

var data=[{"code":5222,"date":3-4-2015},{"code":5222,"date":3-6-2015},{"code":5222,"date":3-7-2015},];

var Unique = d3.set(data, function(d) {return d.code});

Unique returns only '5222', as you expected.

Please, note that d3 converts data to strings in this case, so it might be the case you would need to convert them back to numbers.

Upvotes: 1

Rothrock
Rothrock

Reputation: 1512

I think you need to use nest().

var nest = d3.nest()
  .key(function(d) { return d.code; })
  .entries(data);

That will create a new array with each code only once and an object of all the objects that have that value.

Edit

var data=[{"code":5222,"date":3-4-2015},{"code":5222,"date":3-6-2015},{"code":5222,"date":3-7-2015}];

var nest = d3.nest()
  .key(function(d) { return d.code;})
  .entries(data);

d3.select("#detectors").selectAll("option")
  .data(nest)
  .enter()
    .append("option")
    .text(function(d){ return d.key;})
    .attr("value",function(d){return d.key;});

This code works for me with no errors

Upvotes: 3

Related Questions