多个角度过滤器

时间:2021-01-29 17:13:49

标签: javascript arrays angular filter angular-filters

我正在研究一个考虑三个布尔变量的函数,它过滤一个数组。 假设变量是 a, b, c = false 我的过滤器是

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

它通过数组解析,三个条件是元素是否未定义,元素是否与用户匹配,以及元素是否已定义但与用户不匹配。 所以说arr长度是30,第一组有1个元素,第二组有7个,第三组有22个。如果a和b为真,它应该返回8个元素,如果a和c为真,它应该返回23元素等等。 该 func 应该适用于三个过滤器的任何组合。 然而,事实并非如此。这一次只适用于一个过滤器。 我可能做错了什么?我尝试将 && 更改为 ||但这不起作用(我认为&&无论如何都是正确的方法)

1 个答案:

答案 0 :(得分:3)

根据我对你的问题的理解,应该这样做

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