You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据defaultOption规则过滤selectedOption数组得到预期输出?

解决方案

实现逻辑

  1. 先基于defaultOption构建id到所属分组的映射,方便快速查询每个id归属于哪个分组
  2. 遍历selectedOption统计每个分组最后一次出现的元素索引
  3. 再次遍历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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 19:57:03