Daisy Daisy - 1 year ago 69
Javascript Question

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"}
];


I want to filter(or map, forEach whatever) persons array with students array.
Students array is dynamic, so its length can be changed.

Any ideas?

Answer Source

It can be done with filter along with 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()))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download