我收集了一些元素。
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);
关于javascript - 如何计算数组中的重复项并将计数转换为以下格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62051344/