Singla
Singla

Reputation: 49

Dynamic conditions of array for javascript

const conditionalArray = [
  { name: "line", condition: ">=", value: 5 },
  { name: "revene", condition: "in", value: 6 },
];

const dataTofilter = [
  { line: 3, revene: 4, sale: 3, fridge: "lg" },
  { line: 6, revene: 3, sale: 2, fridge: "samsung" },
];

I have these 2 arrays one is having conditions ( many more can be there) and second is to filter

Final result should be [{ line: 6, revene: 3, sale: 2, fridge: "samsung" }]

Upvotes: 2

Views: 1002

Answers (3)

MikeM
MikeM

Reputation: 13641

Something along the lines of:

const conditionalArray = [
  { name: "line", condition: ">=", value: 5 },
  { name: "revene", condition: "<", value: 6 },
];

const dataTofilter = [
  { line: 3, revene: 4, sale: 3, fridge: "lg" },
  { line: 6, revene: 3, sale: 2, fridge: "samsung" },
];

const conditions = {
  '<': (x, y) => x < y,
  '<=': (x, y) => x <= y,
  '>': (x, y) => x > y,
  '>=': (x, y) => x >= y,
};

const result = dataTofilter.filter(data => {
  for (const el of conditionalArray) {
    if (!conditions[el.condition](data[el.name], el.value)) {
      return false;
    }
  }
  return true;
});

console.log(result);

Upvotes: 2

Behemoth
Behemoth

Reputation: 9370

I'm really not a big fan of it. But I don't see another way as eval() to make the condition work as an actual operator without doing plenty of manual checks. Also the following solution assumes that every item in dataToFilter has a corresponding item in conditionalArray.

const conditionalArray = [
  { name: "line", condition: ">=", value: 5 },
  { name: "revene", condition: "<", value: 6 },
];

const dataTofilter = [
  { line: 3, revene: 4, sale: 3, fridge: "lg" },
  { line: 6, revene: 3, sale: 2, fridge: "samsung" },
];

const result = dataTofilter.filter((item, i) =>
  eval(
    `${item[conditionalArray[i].name]}${conditionalArray[i].condition}${
      conditionalArray[i].value
    }`
  )
);

console.log(result);

Upvotes: 0

Hozeis
Hozeis

Reputation: 1742

const newData = dataTofilter.filter((item) => {
   const passedConditions = [];
   conditionalArray.forEach((cond) => {
       switch(cond.condition){
           case ">":
              passedCondition.push(item[cond.name] > cond.value);
              break;
           case ..... //other conditional checks
       }
     }); //end forEach

     return Arrays.asList(passedCondition).contains(false) === false;
});

If you don't want to use eval you can do something like this. We loop through all the data first and use filter to only return values that pass our conditional check.

We then loop trough the conditional array testing each condition on the single item and save the value to passedConditions. You will need to add the rest of the conditions.

Finally we return wether the passedCondtions array did not contain a false value. This would mean we passed all the conditional checks.

Upvotes: 0

Related Questions