如何判断对象数组是否包含整数数组中的所有值并返回对应布尔结果
判断整数数组元素是否全部存在于对象数组的实现方法
实现逻辑如下:
- 先提取对象数组中用于匹配的字段值(示例中为
id),生成Set结构,将单次查找的时间复杂度降低到O(1) - 调用整数数组的
every方法遍历校验,只要有一个元素不存在就立即返回false,全部存在则返回true
完整代码示例
// 示例数据源 const Sizes = [ { id: 1, }, { id: 2, }, { id: 3, }, { id: 4, }, ]; // 注意不要用Number作为变量名,会和JS内置Number构造函数冲突 const numArray = [1, 2, 3]; // 通用校验函数 const checkAllExist = (intArr, objArr, matchKey) => { const matchValues = new Set(objArr.map(item => item[matchKey])); return intArr.every(val => matchValues.has(val)); } // 测试调用 const result = checkAllExist(numArray, Sizes, 'id'); console.log(result); // 输出:true
边界情况说明
- 如果整数数组为空,
every方法默认返回true,如果业务中空数组需要返回false,可在函数开头加if(intArr.length === 0) return false的判断 - 如果对象数组中存在
undefined、null等异常值,可在生成Set时加过滤逻辑,比如objArr.map(item => item[matchKey]).filter(Boolean)
内容的提问来源于stack exchange,提问作者John w.
相关产品推荐
相关产品推荐

