首页 > 解决方案 > 如何计算数组中的重复项并将计数转换为以下格式?

问题描述

我有一个项目集合。

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 计算的。

请更新片段。

标签: javascript

解决方案


您可以减少数组并检查是否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);


推荐阅读