var students = ["Malcom", "Jayne"];
var persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
我想用学生数组过滤(或映射,forEach)数组。 学生阵列是动态的,所以它的长度可以改变。
有什么想法吗?
答案 0 :(得分:1)
可以使用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()))
答案 1 :(得分:0)
您可以使用permutations()
和Set
。
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);

答案 2 :(得分:0)
您应该能够通过检查firstname
是否在students
数组中来过滤数组:
persons.filter(function(person) { return students.indexOf(person.firstname) >= 0 });
答案 3 :(得分:0)
为此,您可以使用filter()
和includes()
var students = ["Malcom", "Jayne"];
var persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
var r = persons.filter(function(o) {
return students.includes(o.firstname);
});
console.log(r)
答案 4 :(得分:0)
var students = ["Malcom", "Jayne"];
var persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
var filteredPersons = persons.filter(person => students.indexOf(person.firstname) > -1);