如何使用数组条件过滤数组
2016-09-15
91
var students = ["Malcom", "Jayne"];
var persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
我想用学生数组过滤(或映射、forEach 等)人员数组。 学生数组是动态的,因此其长度可以更改。
有什么想法吗?
3个回答
可以使用
filter
和
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()))
Diego ZoracKy
2016-09-15
您可以使用
Set
和
Array#filter
。
var students = ["Malcom", "Jayne"],
persons = [{ firstname: "Malcom", lastname: "Reynolds" }, { firstname: "Kaylee", lastname: "Frye" }, { firstname: "Jayne", lastname: "Cobb" }],
result = persons.filter(function (a) {
return this.has(a.firstname);
}, new Set(students));
console.log(result);
ES6
var students = ["Malcom", "Jayne"],
persons = [{ firstname: "Malcom", lastname: "Reynolds" }, { firstname: "Kaylee", lastname: "Frye" }, { firstname: "Jayne", lastname: "Cobb" }],
result = persons.filter((set => a => set.has(a.firstname))(new Set(students)));
console.log(result);
Nina Scholz
2016-09-15
您应该能够通过检查他们的
firstname
是否在
students
数组中来过滤数组:
persons.filter(function(person) { return students.indexOf(person.firstname) >= 0 });
Steven Schobert
2016-09-15