Javascript dynamic filter over js with array of criterions

const arr = [
   {label : 'lbl1', text: 'txt1'},
   {label : 'lbl2', text: 'txt2'},
   {label : 'lbl3', text: 'txt3'},
   {label : 'lbl4', text: 'txt4'},
   // much more items
];

const filterBy = [
    {label: 'lbl1',text: 'txt1'},
    {label : 'lbl4', text: 'txt4'}
    //may have 0 or more items
];

I want to dynamically filter arr by filterBy. filterBy is coming from the UI… here its just a representation of what the user can pass…

in a static way I would do:

arr.filter(x => (x.text == filterBy[0].text && x.label == filterBy[0].label) ||
   .            (x.text == filterBy[1].text && x.label == filterBy[1].label)
);

Is it possible to chain dynamic criterions in JS? Thanks

Answer

You can easily achieve this result using filter and some

const arr = [
  { label: "lbl1", text: "txt1" },
  { label: "lbl2", text: "txt2" },
  { label: "lbl3", text: "txt3" },
  { label: "lbl4", text: "txt4" },
];

const filterBy = [
  { label: "lbl1", text: "txt1" },
  { label: "lbl4", text: "txt4" },
];

const result = arr.filter(({ label, text }) =>
  filterBy.some((o) => o.label === label && o.text === text)
);

console.log(result);