Home > front end >  How to check if the item satisfies all of the conditions from the conditions array?
How to check if the item satisfies all of the conditions from the conditions array?

Time:02-04

I want to make a function that filters the items by checking if they satisfy all of the conditions provided. The function receives 2 parameters: (data, include):

data: [
    { user: "[email protected]", rating: 20, disabled: false },
    { user: "[email protected]", rating: 14, disabled: false },
    { user: "[email protected]", rating: 25, disabled: true }
  ]


include: [{ disabled: false }, { rating: 20 }]

With the data above, for example, the function should return the array with only one entry:

[{ user: "[email protected]", rating: 20, disabled: false }]

Because that entry has both disabled: false and rating: 20.

So my function is:

const filterInclude = (data, include) => {
  const result = [];

  data.forEach((item) => {
    for (let [key, value] of Object.entries(item)) {
      include.forEach((cond) => {
        if (cond.hasOwnProperty(key) && cond[key] === value) {
          result.push(item);
        }
      });
    }
  });

  return result;
};

It works correctly when the include array has only 1 item, for example:

include: [{ disabled: false }]

However, when there are multiple conditions, it's not working correctly because it pushes the item to the result if it satisfies at least 1 condition.

How to improve this function to make it work correctly and push the item to the result only when it satisfies all of the conditions?

CodePudding user response:

Just use the filter function as follows:

 const filterInclude = ({data, disabled, rating })=> data.filter((el) => el.disabled === disabled && el.rating === rating )

Use it as follows:

const data= [
    { user: "[email protected]", rating: 20, disabled: false },
    { user: "[email protected]", rating: 14, disabled: false },
    { user: "[email protected]", rating: 25, disabled: true }
  ];

console.log(filterInclude({data, disabled: false, rating: 20}))

CodePudding user response:

So I accomplished what the task requires. Here is the improved code in case somebody needs something similar in the future:

const checkInclude = (item, include) => {
  let numOfSatisfied = 0;

  conditions: for (let cond of include) {
    for (let [key, value] of Object.entries(item)) {
      if (cond.hasOwnProperty(key) && cond[key] === value) {
        numOfSatisfied  ;
        continue conditions;
      }
    }
  }

  return numOfSatisfied === include.length ? true : false;
};

const filterInclude = (data, include) => {
  const result = data.filter((item) => checkInclude(item, include));

  return result;
};
  • Related