如何使用数组条件过滤数组 [英] How to filter array with array condition
本文介绍了如何使用数组条件过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var students = ["Malcom", "Jayne"];
var persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
我想用学生数组过滤(或映射,forEach随便什么)人数组。
学生数组是动态的,因此可以更改其长度。
I want to filter(or map, forEach whatever) persons array with students array. Students array is dynamic, so its length can be changed.
有什么想法吗?
推荐答案
可以使用过滤器
和 some
来完成。
var students = ["Malcom", "Jayne"];
var persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
console.log(persons.filter(person => students.some(student => student == person.firstname)))
// An advice, maybe you want to put everything to lower case
// to prevent a wrong result because of case mismatch
// (e.g. "Malcom" !== "malcom").
// It would be:
persons.filter(person => students.some(student => student.toLowerCase() === person.firstname.toLowerCase()))
这篇关于如何使用数组条件过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文