Home > Mobile >  How to create dynamic array filter expression?
How to create dynamic array filter expression?

Time:12-08

I need a function to filter array of objects based on given structure of object. So I have this object:

{
    "2": [
        {
            "fd_id": 16,
           ...others
        }
    ],
    "3": [
        {
            "fd_id": 2,
            ...others
        },
        {
            "fd_id": 3,
           ...others
        }
    ]
}

I would like to filter another array based on this object. Like this;

const result = products.filter(item => {
                // returns array of numbers [1, 2, 3]
                const filters = item.filters;
                if(filters){
                    // Here must be refactored
                    return ((filters.includes(givenObj[2][0].fd_id))
                        && (filters.includes(givenObj[3][0].fd_id) || filters.includes(givenObj[3][1].fd_id)));
                }
            });

But this function must be dynamic. Because the input object may change. So for between each parent "&&", and between each children "||" condition must be applied. Thanks for any help. This is the link to example https://jsfiddle.net/cadkt86n/

CodePudding user response:

A function to loop the data will help.

My Logic

  • Generate the list of fd_ids from the groups using Array.map
  • Filter products array. Check for the matching combination in filters node of products array. Condition is there should be a matching combination in each nodes of fdIdList array.

Working Fiddle

var groups = {
  "2": [
    { "fd_id": 16, "fd_fRef": 2, "fd_ad": "35 - 50", "fd_siraNo": 255, "checked": true }
  ],
  "3": [
    { "fd_id": 2, "fd_fRef": 3, "fd_ad": "KURU", "fd_siraNo": 255, "checked": true },
    { "fd_id": 3, "fd_fRef": 3, "fd_ad": "KARMA", "fd_siraNo": 255, "checked": true }
  ]
}

// Aggregates the list of fd_id s - This wil be an array of arrays
// [[16],[2,3]] => This will be the value
const fdIdList = Object.values(groups).map(a => a.map(b => b.fd_id));

var products = [
  {
    "id": 1,
    "filters": [2, 3, 4, 13, 16, 17, 18, 19, 31, 48, 309, 318],
  },
  {
    "id": 2,
    "filters": [2, 3, 4, 13, 15, 17, 18, 19, 31, 48, 309, 318],
  }
];


// Check if there is a common element in each node of fdIdList
var result = products.filter(item => {
  const filters = item.filters;
  if (filters) {
    let isFound = true;
    fdIdList.forEach(idListNode => {
      isFound = isFound && idListNode.filter(value => filters.includes(value)).length > 0;
    })
    return isFound
  }
});

console.log(result)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related