Search code examples
javascriptarraysangularfilterangular-filters

Multiple filters in angular


I am working on a function that takes into consideration three boolean variables, and it filters an array. Lets say the vars are a, b, c = false and the filter I have is

let newArr = this.original.filter(x =>
  (!this.a || x === undefined) &&
  (!this.b || x === this.name) &&
  (!this.c || ((x !== undefined) && (x !== this.name))));

Its parsing through an array and the three conditions are if the element is undefined, if the element matches the user and if the element is defined but does not match the user. So say the arr length is 30, the first group has 1 element, the second has 7 and the third have 22. If a and b are true, it should return 8 elements, and if a and c are true, it should return 23 elements, and so on. The func should work with any and every combination of the three filters. However, this isn't the case. This only works great with one filter at a time. What could I be doing wrong? I tried changing the && to || but that didn't work (and I think && is the right way anyway)


Solution

  • From what I understood of your question, this should do it

    let newArr = this.original.filter(x =>
      (this.a && x === undefined) ||
      (this.b && x === this.name) ||
      (this.c && ((x !== undefined) && (x !== this.name))));