javascript - 我想计算时间统计为真的次数并计算针对唯一 ID 重复的日期数
问题描述
使用 id 必须为 stat 和 ttrf 创建一个计数器,并创建具有 name、id、stat 数和 ttrf 数的新数据,这些数据与唯一 ID 重复
data = [
0: {id: "51a", name: "Henry", team: "SPP", stat: "true", ttrf: "05/08/2020"}
1: {id: "5ea", name: "James", team: "BOPS", stat: "true", ttrf: "05/08/2020"}
2: {id: "51a", name: "Henry", team: "SPP", stat: "false", ttrf: "05/08/2020"}
3: {id: "5ea", name: "James", team: "BOPS", stat: "true", ttrf: "05/08/2020"}]
要获得的输出:
data = [
0: {id: "51a", name: "Henry", team: "SPP", stat: 1, ttrf: 2}
1: {id: "5ea", name: "James", team: "BOPS", stat: 2, ttrf: 2}]
解决方案
在这里,我使用reduce
了方法来解决这个问题。您可以检查此解决方案。
const data = [
{ id: "51a", name: "Henry", team: "SPP", stat: "true", ttrf: "05/08/2020" },
{ id: "5ea", name: "James", team: "BOPS", stat: "true", ttrf: "05/08/2020" },
{ id: "51a", name: "Henry", team: "SPP", stat: "false", ttrf: "05/08/2020" },
{ id: "5ea", name: "James", team: "BOPS", stat: "true", ttrf: "05/08/2020" },
];
const newData = data.reduce((store, obj) => {
const statVal = obj.stat === "true" ? 1 : 0;
const ttrfVal = obj.ttrf ? 1 : 0;
if (!store[obj.id]) {
store[obj.id] = obj;
obj.ttrfDates = new Set();
obj.ttrfDates.add(obj.ttrf);
store[obj.id].ttrf = ttrfVal;
store[obj.id].stat = statVal;
} else {
if (!(obj.stat === "true" && store[obj.id].ttrfDates.has(obj.ttrf))) {
store[obj.id].ttrf++;
}
store[obj.id].stat += statVal;
}
return store;
}, {});
const modifiedData = Object.values(newData).filter(
(data) => data.ttrfDates && delete data.ttrfDates
);
console.log(modifiedData);
推荐阅读
- lisp - 使用 Common LISP 运行爬山搜索的问题
- python - 如何在不使用线程/后台作业的情况下同时使服务器端循环无休止和非阻塞?
- android - 带有过滤器的 Recyclerview 中的 Firestore 一次性获取与实时侦听器
- macos - Unable to locate .npm/_logs/ folder on mac
- php - why my host add automaticlly add secure flag to cookie?
- sql-server - 从 SQL Server 中的 VARBINARY(MAX) 下载 .PDF
- javascript - axios实例promise.all错误处理
- sql - SELECT $b 没有将智能感知显示为错误,但会引发错误。这种情况背后的原因是什么?
- python - 尝试在opencv imread函数中使用多个图像但没有得到
- laravel - 当我运行命令 npm install 它给出错误 npm ERR cb() never called