You need to enable JavaScript to run this app. 如何基于另一个数组的取值过滤对象数组?JavaScript实现方案
优惠活动
大模型
产品
解决方案
定价
更多

如何基于另一个数组的取值过滤对象数组?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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 08:15:02