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

如何筛选出满足demographics果蔬条件的people数组对象?

筛选符合条件的人员对象

需求说明

需要从people数组中筛选出同时满足以下两个条件的对象:

  • 其fruit数组包含demographics.fruit中的至少一种水果(apple或mango)
  • 其veg数组包含demographics.veg中的指定蔬菜(asparagus)

原生JavaScript实现

可以用数组的filter方法结合some、includes完成筛选:

const filteredPeople = people.filter(person => {
  // 检查是否有至少一种匹配的水果
  const hasMatchingFruit = person.fruit.some(fruit => demographics.fruit.includes(fruit));
  // 检查是否包含指定蔬菜
  const hasMatchingVeg = person.veg.includes(demographics.veg[0]);
  // 两个条件都满足才保留
  return hasMatchingFruit && hasMatchingVeg;
});

console.log(filteredPeople);

Underscore.js实现

如果使用Underscore工具,可通过_.filter、_.some和_.includes实现,写法更简洁:

const filteredPeople = _.filter(people, person => {
  const hasMatchingFruit = _.some(person.fruit, fruit => _.includes(demographics.fruit, fruit));
  const hasMatchingVeg = _.includes(person.veg, demographics.veg[0]);
  return hasMatchingFruit && hasMatchingVeg;
});

console.log(filteredPeople);

两种方法都会得到预期结果:

[{
    name: "Dave",
    fruit: ["apple", "pear"],
    veg: ["asparagus", "peas"]
},
{
    name: "Alice",
    fruit: ["mango", "peach"],
    veg: ["asparagus"]
}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 13:49:59