How to implement a multifilter on data in a table?

  • 0
    Test dataset:
    const data = [
    {type: "TYPE1", name: "someName1", scope: "scope1", source: "someSource1", additionalType: "ADDITIONAL_TYPE1"},
    {type: "TYPE2", name: "someName2", scope: "scope2", source: "someSource2", additionalType: "ADDITIONAL_TYPE2"},
    {type: "TYPE3", name: "someName3", scope: "scope3", source: "someSource3", additionalType: "ADDITIONAL_TYPE3"},
    ];

    The filter object that I create dynamically:
    const filters = {
    type: [ "TYPE1" ], // фильтр по селекту из списка
    name: "someName1",  // фильтр по текстовому полю
    scope: [ "scope1", "scope2", "scope3" ], // фильтр по селекту из списка
    source: "someSource1", // фильтр по текстовому полю
    additionalType: ["ADDITIONAL_TYPE1", "ADDITIONAL_TYPE2", "ADDITIONAL_TYPE3" ]  // фильтр по селекту из списка
    }


    How to get a suitable element from the data array from the given filters?
    [{type: "TYPE1", name: "someName1", scope: "scope1", source: "someSource1", additionalType: "ADDITIONAL_TYPE1"}]
    JavaScript Anonymous, Oct 8, 2020

  • 1 Answers
  • 0
    Object.entries(filters).reduce((items, [ k, v ]) => {
    return items.filter(Array.isArray(v)
    ? item => v.includes(item[k])
    : item => v === item[k]
    );
    }, data)
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!