gpt4 book ai didi

d3.js - 交叉过滤查询

转载 作者:行者123 更新时间:2023-12-03 10:01:46 30 4
gpt4 key购买 nike

是否可以过滤具有数组作为值的交叉过滤器数据集?

例如,假设我有以下数据集:

var data = [
{
bookname: "the joy of clojure",
authors: ["Michael Fogus", "Chris Houser"],
tags: ["clojure", "lisp"]
},
{
bookname: "Eloquent Ruby",
authors: ["Russ Olsen"],
tags: ["ruby"]
},
{
bookname: "Design Patterns in Ruby",
authors: ["Russ Olsen"],
tags: ["design patterns", "ruby"]
}
];

是否有一种简单的方法可以访问由特定标签标记的书籍?还有那些有特定作者的书?到目前为止,我理解如何使用 crossfilter 的方式让我做了这样的事情:
var filtered_data = crossfilter(data);
var tags = filtered_data.dimension(function(d) {return d.tags});
var tag = tags.group();

然后当我访问分组时(像这样):
tag.all()

我明白了:
[{key: ["clojure", "lisp"], value: 1}, 
{key: ["design patterns", "ruby"], value: 1},
{key: ["ruby"], value: 1}]

当我宁愿拥有这个时:
[{key: "ruby", value: 2}, 
{key: "clojure", value: 1},
{key: "lisp", value: 1},
{key: "design patterns", value: 1}]

最佳答案

我在下面的代码中添加了注释。大图:使用reduce功能。

var data = ...
var filtered_data = crossfilter(data);
var tags = filtered_data.dimension(function(d) {return d.tags});

tags.groupAll().reduce(reduceAdd, reduceRemove, reduceInitial).value()

请注意我如何使用 groupAll() 而不是 组() b/c 我们希望我们的 reduce 函数(定义如下)对一组而不是 3 组进行操作。

现在 reduce 函数应该是这样的:
/*
v is the row in the dataset

p is {} for the first execution (passed from reduceInitial).
For every subsequent execution it is the value returned from reduceAdd of the prev row
*/
function reduceAdd(p, v) {
v.tags.forEach (function(val, idx) {
p[val] = (p[val] || 0) + 1; //increment counts
});
return p;
}

function reduceRemove(p, v) {
//omitted. not useful for demonstration
}

function reduceInitial() {
/* this is how our reduce function is seeded. similar to how inject or fold
works in functional languages. this map will contain the final counts
by the time we are done reducing our entire data set.*/
return {};
}

关于d3.js - 交叉过滤查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12044935/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com