javascript 如何从数据中选择 d3.js 中的唯一值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28572015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:11:48  来源:igfitidea点击:

How to select unique values in d3.js from data

javascripthtmld3.js

提问by ahmohamed

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

我正在使用以下代码使用 d3.js 填充我的 Combobox

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?

存在具有相同名称的不同行。组合框正在填充这些重复的名称。例如,在多行中,道路名称是 I-80。但在组合框中,我只想看到 I-80 一次。我怎样才能做到这一点?

回答by ahmohamed

Filter your data retaining unique keys only by d3.map

仅通过以下方式过滤保留唯一键的数据 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;});

回答by Nevershowmyface

Try this:

试试这个

/* file.csv
name_of_my_header
mom
dad
brother
sister
dog
*/
button.onclick = function() {
    var s = d3.select("#road");
    d3.csv(prompt("URL please"), function(dataset){
        dataset.forEach(function(row) {
            s.append("option").text(row["name_of_my_header"]);
        })
    })
}
<select id="road">
</select>
<button id="button">Is it?</button>