如何按特定规则计算对象数组中userId属性的唯一值数量
解决userId计数需求问题
问题描述
现有如下对象数组:
const array = [ { _id: '1', userId: '5' }, { _id: '2', userId: null }, { _id: '3', userId: null }, { _id: '4', userId: '1' }, { _id: '5', userId: '2' }, { _id: '6', userId: '4' }, { _id: '7', userId: '4' }, { _id: '8', userId: null }, { _id: '9', userId: null }, { _id: '10', userId: '2' } ];
需要统计userId值的计数,规则为:
null值每次出现都单独计数- 非
null的userId值重复出现仅计数一次
原使用的函数无法正确处理null值:
const uniqueItems = (list, key) => list.reduce( (resultSet, item) => resultSet.add(typeof key === "string" ? item[key] : key(item)), new Set() ).size; uniqueItems(array, "userId");
问题原因
原函数利用Set的去重特性统计数量,但Set会对所有值去重,包括null——多个null只会被存储一次,导致null的计数被错误合并。
解决方案
分开统计两类值:用Set存储非null的唯一userId,同时单独计数null的出现次数,最后将两者相加得到总计数。
方法一:forEach遍历统计
const countUserId = (array) => { const uniqueNonNullIds = new Set(); let nullCount = 0; array.forEach(item => { const userId = item.userId; if (userId === null) { nullCount++; } else { uniqueNonNullIds.add(userId); } }); return uniqueNonNullIds.size + nullCount; }; // 测试调用 console.log(countUserId(array)); // 输出:8
方法二:reduce整合统计
const countUserId = (array) => { const { uniqueCount, nullCount } = array.reduce((acc, item) => { const userId = item.userId; if (userId === null) { acc.nullCount++; } else if (!acc.uniqueIds.has(userId)) { acc.uniqueIds.add(userId); acc.uniqueCount++; } return acc; }, { uniqueIds: new Set(), uniqueCount: 0, nullCount: 0 }); return uniqueCount + nullCount; }; // 测试调用 console.log(countUserId(array)); // 输出:8
结果说明
示例数组中,非null的唯一userId有'5'、'1'、'2'、'4'共4个,null出现了4次,总计数为4+4=8。
内容的提问来源于stack exchange,提问作者Abhishek Goswami
相关产品推荐
相关产品推荐

