如何筛选出满足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
相关产品推荐
相关产品推荐

