简体   繁体   English

如何避免循环重复?

[英]How to avoid loops duplication?

There is a specific logic for filtering collection:过滤集合有一个特定的逻辑:

    let rows = (collection || []).filter((item: any) => {
      const { country, year, productType, units, productSubtype } = item;
      const cond1 = unitsPlain.length ? unitsPlain.includes(units) : true;
      const cond3 = years.includes(year);
      const cond2 = country === value;
      const cond4 = productType === key && !productSubtype;

      return cond1 && cond2 && cond3 && cond4;
    });

    if (!rows.length) {
      rows = collection.filter((item: any) => {
        const { country, year, productType, productSubtype } = item;
        const cond3 = years.includes(year);
        const cond2 = country === value;
        const cond4 = productSubtype === key && !productType;

        return cond2 && cond3 && cond4;
      });
    }

    if (!rows.length) {
      rows = collection.filter((item: any) => {
        const { country, year, productType, productSubtype } = item;
        const cond3 = years.includes(year);
        const cond2 = country === value;
        const cond4 = productSubtype === key || productType === key;

        return cond2 && cond3 && cond4;
      });
    }

As you noticed I try to launch the next loop to find elements of prev returns empty result.正如您所注意到的,我尝试启动下一个循环以查找 prev 的元素返回空结果。

How to improve it?如何改进?

You can chain filters您可以链接过滤器

let rows = (collection || []).filter(callbackFn).filter(callbackFn)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM