如何根据defaultOption规则过滤selectedOption数组得到预期输出?
解决方案
实现逻辑
- 先基于
defaultOption构建id到所属分组的映射,方便快速查询每个id归属于哪个分组 - 遍历
selectedOption统计每个分组最后一次出现的元素索引 - 再次遍历
selectedOption,只保留无分组的元素、以及是所在分组最后一次出现的元素
完整实现代码
// 构建id到所属分组的映射 const idToGroupMap = new Map(); defaultOption.forEach(group => { const groupId = group.item_select.value; group.options.forEach(opt => { idToGroupMap.set(opt.value, groupId); }); }); // 统计每个分组最后一次出现的索引 const groupLastIndex = new Map(); selectedOption.forEach((item, idx) => { const groupId = idToGroupMap.get(item.id); if (groupId) groupLastIndex.set(groupId, idx); }); // 筛选符合要求的元素 const expected_output = selectedOption.filter((item, idx) => { const groupId = idToGroupMap.get(item.id); return !groupId || groupLastIndex.get(groupId) === idx; });
输出结果
运行上述代码后得到的expected_output完全符合要求:
[ { "count": 12, "id": "16" }, { "count": 2, "id": "8" }, { "count": 4, "id": "15" }, { "count": 1, "id": "6" }, { "count": 34, "id": "19" } ]
内容的提问来源于stack exchange,提问作者dev
相关产品推荐
相关产品推荐

