javascript - 如何计算数组中的重复项并将计数转换为以下格式?
问题描述
我有一个项目集合。
items = [
{name: 'Thomas', id: '234234', 'job': 'painter'},
{name: 'Jonathan', id: '435123', 'job': 'driver'},
{name: 'Thomas', id: '234234', 'job': 'driver'},
{name: 'Mark', id: '767445', 'job': 'mechanic'},
]
我想要实现的是,我想以下列方式映射重复的计数。
预期结果结构:
duplicateCount = {
id: {
name: string;
count: number;
}
}
其中 id 是上述数组(项目)中的用户 id,name 是用户名,count 是重复数。
这里的重复是根据 id 计算的。
例子:
duplicateCount = {
234234: {
name: 'Thomas',
count: 2,
},
435123: {
name: 'Jonathan',
count: 1,
},
767445: {
name: 'Mark',
count: 1,
},
}
/******* explanation: here take one item ***********/
234234: {
name: 'Thomas',
count: 2,
},
// 234234 is the user id & count is the duplication number.
/***********************************/
// we can ignore other props such as job. only two fields are required.
提出一些想法。
更新 对不起我错过了那个
更新:这里的重复是根据 id 计算的。
请更新片段。
解决方案
您可以减少数组并检查是否id
存在,然后增加计数或分配一个新对象。
var items = [{ name: 'Thomas', id: '234234', 'job': 'painter' }, { name: 'Jonathan', id: '435123', 'job': 'driver' }, { name: 'Thomas', id: '234234', 'job': 'driver' }, { name: 'Mark', id: '767445', 'job': 'mechanic' }],
counts = items.reduce((r, { name, id }) => {
if (r[id]) r[id].count++;
else r[id] = { name, count: 1 };
return r;
}, {});
console.log(counts);
推荐阅读
- css - Boostrap 4 选项卡 - 如何阻止文本换行?
- laravel - 有时需要验证多个上传背包字段
- solidity - 了解松露测试
- android - 无法更改应用程序中操作栏的颜色
- reactjs - React.FC 可以接收元组作为未命名的参数吗?
- python - PySpark 和 SQL:修复运行高阶函数时的类型错误
- cluster-analysis - 在r中使用tsclust后如何获取质心值
- python - pandas 系列默认的 rank 函数有什么作用?
- python - 我无法使用 iter_rows() 来迭代 excel 并将单元格值添加为字典列表
- api - 无法通过 RestAssured 发布值