【发布时间】:2019-12-30 05:13:09
【问题描述】:
我正在尝试根据数据属性中是否存在某些关键字来过滤地图上的数据点。例如,按音乐流派过滤点,即显示“流派”属性包含以下任一关键字的所有点:“摇滚”、“流行”、“独立”。
它几乎可以工作,但我不能完全让 D3 过滤器方法在数组上工作。这是一个例子:
//When "Rock Genre" radio button is instantiated, display only "Rock" events
d3.selectAll("#rockPopGenre").on("change", function() {
resetDisplay()
display = this.checked ? "none" : "#ffba00";
display2 = this.checked ? "none" : "black";
x = ["Rock","Pop","Indie"]
genreMatch(x)
});
//Genre matching function which filters points based on an array of key-words
function genreMatch (genreType) {
var genreType
for (i=0; i<genreType.length; i++){
d3.selectAll(".events")
.filter(function(d) {
return (!d.Genre.includes(genreType[i]))
})
.style("fill", display)
.style("stroke", display2)
}
}
d.Genre 示例:
"Genre": "Standup, Comedy Rock, Comedy, Standup Comedy, Funny, Humor"
"Genre": "Genres: Alternative Rock, Alternative, Pop"
"Genre": "Indie, Indie Electronic, Rock, Alternative"
上述方法仅部分有效。例如,它只显示包含关键字“Rock”的点,但会排除包含“Pop”的点。我想根据所有关键字过滤数据:即如果 d.Genre 在字符串中包含“Rock”、“Pop”或“Indie”,则显示这些点,并隐藏不符合该条件的点。
我不太确定如何实现这一点。我认为问题在于代码分别过滤数组中的每个关键字,而不是将数组视为要匹配的一组单词。提前致谢。
【问题讨论】:
-
你为什么过滤
d.Genre而不包括genreType[i]?d.Genre是什么样的?你能发布一个最小的例子吗? -
我正在过滤“不包括”,因为对于那些不符合关键字标准的点,我将显示设置为“非”。
标签: javascript arrays d3.js filter