Filter array of objects with another array of objects
With Ecma script 6.
const myArrayFiltered = myArray.filter( el => {
return myfilter.some( f => {
return f.userid === el.userid && f.projectid === el.projectid;
});
});
Function:
const filterObjectArray = (arr, filterArr) => (
arr.filter( el =>
filterArr.some( f =>
f.userid === el.userid && f.projectid === el.projectid
)
)
);
console.log(filterObjectArray(myArray, myFilter))
Link to example
In response to Andy answer above, which I believe should be marked now as answer., if you are looking for exact opposite behavior, use every with negation, something like this.
const result = masterData.filter(ad =>
filterData.every(fd => fd.userid !== md.userid));
result
contains all masterData
except filterData
.
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);
You can put a couple of array methods to use here - filter
and some
. They're available in all recent browsers, and there are polyfills available for the older browsers.
const 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" }];
const myFilter = [{ userid: "101", projectid: "11" }, { userid: "102", projectid: "12" }, { userid: "103", projectid: "11"}];
const myArrayFiltered = myArray.filter((el) => {
return myFilter.some((f) => {
return f.userid === el.userid && f.projectid === el.projectid;
});
});
console.log(myArrayFiltered);