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

如何使用Lodash筛选对象数组:找出未存在于已选列表中的选项

解决方法:找出未被选中的选项对象

嘿,我来帮你搞定这个需求!你需要从optionSelection里筛选出那些没在selectedItems中出现过的对象,对吧?下面给你两种实用的方案:

方案一:基础数组方法实现

先用map提取selectedItems里所有商品的id,再用filter结合includes筛选出不在这个id列表里的选项:

// 提取已选中的所有item的id
const selectedIds = selectedItems.map(entry => entry.item.id);
// 筛选未被选中的选项
const unselectedOptions = optionSelection.filter(option => !selectedIds.includes(option.id));

方案二:用Set优化查找效率

如果你的数据量比较大,推荐用Set来存储已选中的id——因为Set的has方法查找时间复杂度是O(1),比数组的includes(O(n))效率更高:

// 将已选中的id存入Set
const selectedIdSet = new Set(selectedItems.map(entry => entry.item.id));
// 筛选未被选中的选项
const unselectedOptions = optionSelection.filter(option => !selectedIdSet.has(option.id));

测试结果

针对你提供的示例数据,两种方法都会得到相同的结果:

// unselectedOptions的输出:
[
  { id:4, description:"Bottle" },
  { id:5, description:"Glass" }
]

内容的提问来源于stack exchange,提问作者Ralph H

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 07:07:33