【发布时间】:2021-04-20 08:48:06
【问题描述】:
我正在尝试使用d3-array 生成对象数组的两个摘要:
- 每位老师都做了哪些动作?
- 每位教师编辑了哪些帖子?
这是我目前的做法:
const data = [
{ post_id: 47469, action: "reply", teacher_username: "John" },
{ post_id: 47469, action: "edit", teacher_username: "John" },
{ post_id: 47468, action: "reply", teacher_username: "John" },
{ post_id: 47465, action: "reply", teacher_username: "Mary" },
{ post_id: 47465, action: "edit", teacher_username: "Mary" },
{ post_id: 47467, action: "edit", teacher_username: "Mary" },
{ post_id: 46638, action: "reply", teacher_username: "Paul" },
];
const teacherSummary = [
...d3.rollup(
data,
(x) => x.length,
(d) => d.teacher_username,
(d) => d.action
),
]
.map((x) => {
return {
teacher_username: x[0],
num_edits: x[1].get("edit") || 0,
num_replies: x[1].get("reply") || 0,
};
})
.sort((a, b) => d3.descending(a.num_edits, b.num_edits));
// [
// { "teacher_username": "Mary", "num_edits": 2, "num_replies": 1 },
// { "teacher_username": "John", "num_edits": 1, "num_replies": 2 },
// { "teacher_username": "Paul", "num_edits": 0, "num_replies": 1 }
// ]
const postIdsByTeacher = d3.rollups(
data.filter((x) => x.action === "edit"),
(v) => [...new Set(v.map((d) => d.post_id))].join(", "), // Set() is used to get rid of duplicate post_ids
(d) => d.teacher_username
);
// [
// ["John","47469"],
// ["Mary","47465, 47467"]
// ]
我对输出格式很灵活。我想优化的是效率和清晰度:
- 我可以在一个
rollup电话中获得两个摘要吗?也许通过将edited_post_ids添加到teacherSummary。 - 似乎应该有一种更优雅的方法来替换
[...Map/Set]调用
编辑:出于好奇,我也使用alasql 尝试了这种方法。除了edited_post_ids 中的空值外,它几乎可以工作。
sql = alasql(`
select
teacher_username,
count(case when action = 'reply' then 1 end) num_replies,
count(case when action = 'edit' then 1 end) num_edits,
array(case when action = 'edit' then post_id end) as edited_post_ids
from ?
group by teacher_username
`, [data])
// [
// { teacher_username: "John", num_replies: 2, num_edits: 1, edited_post_ids: [null, 47469, null], },
// { teacher_username: "Mary", num_replies: 1, num_edits: 2, edited_post_ids: [null, 47465, 47467], },
// { teacher_username: "Paul", num_replies: 1, num_edits: 0, edited_post_ids: [null], },
// ];
【问题讨论】:
标签: javascript arrays d3.js alasql