JavaScript实现数组对象公共元素分组构建团队结构
解决JavaScript中用户关联笔记本的团队分组问题
需求:将给定的usersByNotebooks数组转换为teams数组,规则是把存在共同用户的笔记本归为同一团队,每个团队整合对应的notebookId到notebooksOnTeam,同时汇总该团队的所有关联用户到usersOnTeam。
源数据示例
const usersByNotebooks = [ { "notebookId": "abc", "users": [1, 2, 3, 4] }, { "notebookId": "cde", "users": [2, 3, 4] }, { "notebookId": "fgh", "users": [3, 4, 5] }, { "notebookId": "qqq", "users": [33, 16, 12] } ];
目标数据示例
const teams = [ { "notebooksOnTeam": ["abc", "cde", "fgh"], "usersOnTeam": [1, 2, 3, 4, 5] }, { "notebooksOnTeam": "qqq", "usersOnTeam": [33, 16, 12] } ];
实现方案
核心思路是用映射表记录每个用户所属的团队索引,遍历每个笔记本时,检查其用户是否已有归属团队,若有则合并当前笔记本到对应团队;若没有则创建新团队。最后统一处理去重和格式调整。
function convertToTeams(usersByNotebooks) { const teams = []; // 记录用户ID到团队索引的映射,快速定位归属团队 const userToTeamIndex = new Map(); for (const notebook of usersByNotebooks) { let targetTeamIndex = null; // 检查当前笔记本的用户是否已有归属团队 for (const userId of notebook.users) { if (userToTeamIndex.has(userId)) { targetTeamIndex = userToTeamIndex.get(userId); break; } } if (targetTeamIndex !== null) { // 合并到已有团队 const targetTeam = teams[targetTeamIndex]; targetTeam.notebooksOnTeam.push(notebook.notebookId); // 合并用户并去重 const mergedUsers = new Set([...targetTeam.usersOnTeam, ...notebook.users]); targetTeam.usersOnTeam = Array.from(mergedUsers); // 更新映射表,确保当前笔记本所有用户都指向该团队 for (const userId of notebook.users) { userToTeamIndex.set(userId, targetTeamIndex); } } else { // 创建新团队 const newTeam = { notebooksOnTeam: [notebook.notebookId], usersOnTeam: Array.from(new Set(notebook.users)) }; const newIndex = teams.length; teams.push(newTeam); // 记录当前笔记本所有用户的团队索引 for (const userId of notebook.users) { userToTeamIndex.set(userId, newIndex); } } } // 调整格式:单个笔记本的团队,将数组转为字符串 return teams.map(team => ({ ...team, notebooksOnTeam: team.notebooksOnTeam.length === 1 ? team.notebooksOnTeam[0] : team.notebooksOnTeam })); } // 测试调用 const teams = convertToTeams(usersByNotebooks); console.log(teams);
逻辑说明
- 用户-团队映射:用
Map存储用户与团队的关联关系,避免重复遍历团队数组,提升效率。 - 团队合并:当检测到当前笔记本的用户已属于某个团队时,直接合并笔记本ID和用户列表,确保团队数据完整。
- 新团队创建:若当前笔记本的用户无归属团队,直接创建新团队并更新映射关系。
- 格式适配:最后统一调整
notebooksOnTeam的格式,匹配目标数据的要求。
内容的提问来源于stack exchange,提问作者deadant88
相关产品推荐
相关产品推荐

