如何基于另一个数组的取值过滤对象数组?JavaScript实现方案
实现方案
基础实现
直接基于Array.filter搭配Array.includes即可实现动态匹配,无需硬编码国家值,同时兼容空入参的处理逻辑:
const matchCriteria = (countries) => { // 传入空数组直接返回空结果 if (!countries || countries.length === 0) return [] // 过滤出国家属性命中入参数组的人员对象 return people.filter(person => countries.includes(person.country)) }
高性能优化方案
如果入参countries的元素量级较大,可以先转为Set结构提升查询效率(Set.has时间复杂度为O(1),远优于Array.includes的O(n)):
const matchCriteria = (countries) => { if (!countries || countries.length === 0) return [] const allowedCountries = new Set(countries) return people.filter(person => allowedCountries.has(person.country)) }
如果需要适配动态传入的人员数组,可调整函数入参设计:
const matchCriteria = (people, countries) => { if (!countries || countries.length === 0) return [] const allowedCountries = new Set(countries) return people.filter(person => allowedCountries.has(person.country)) } // 调用示例 const result = matchCriteria(people, ["PT", "ES", "FR"])
效果验证
传入示例中的["PT", "ES", "FR"]调用函数,返回结果如下:
[ {name: "Tom", country: "ES"}, {name: "Amy", country: "FR"}, {name: "Ava", country: "PT"} ]
传入空数组时返回空数组,完全符合要求。
内容的提问来源于stack exchange,提问作者TiagoRibeiro
相关产品推荐
相关产品推荐

