Daisy Daisy - 2 months ago 6
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

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()))

Comments