Search code examples
javascriptjqueryarraysobjectfilter

Filter array of objects with another array of objects


This question is similar to this one Jquery filter array of object with loop but this time I need to do the filter with an array of objects.

Exemple:

I have an array of objects like this:

myArray = [
{
    userid: "100", 
    projectid: "10",
    rowid: "0"
},
{
    userid: "101", 
    projectid: "11",
    rowid: "1"},
{    
    userid: "102", 
    projectid: "12",
    rowid: "2"},
{    
    userid: "103", 
    projectid: "13",
    rowid: "3"
},
{    
    userid: "101", 
    projectid: "10",
    rowid: "4"
}
...]

I want to filter it with an array like this:

myFilter = [
{
    userid: "101", 
    projectid: "11"
},
{
    userid: "102", 
    projectid: "12"
},
{
    userid: "103", 
    projectid: "11"
}]

and return this (the userid and the projectid in myFilter need to match the userid and the projectid in myArray):

myArrayFiltered = [
{
    userid: "101", 
    projectid: "11",
    rowid: "1"
},
{
    userid: "102", 
    projectid: "12",
    rowid: "2"
}]

How can I do that ?


Solution

  • var filtered = [];
    
    for(var arr in myArray){
       for(var filter in myFilter){
           if(myArray[arr].userid == myFilter[filter].userid && myArray[arr].projectid == myFilter[filter].projectid){
              filtered.push(myArray[arr].userid);
             }
       }
    }
    console.log(filtered);