我试图过滤另一个数组

时间:2019-04-24 08:33:34

标签: typescript angular6

我正在尝试在此场景的另一个症状中过滤数组。

我的数据和代码如下:

illnesses = [

      {"cause": "abc", "symptoms": ["A", "B", "C"]},   
      {"cause": "def", "symptoms": ["g", "s", "k", "j"]}  
]


filterCauses(searchString: string){
    return this.illnesses.filter(
      (c) => {
        for (let i = 0; i < this.cause.length; i++) {
          c.symptoms.filter( d => d.symptoms[i].toLowerCase().indexOf(searchString.toLowerCase()) !== -1)
        }
      }
    )
}

2 个答案:

答案 0 :(得分:0)

filterCauses(searchString: string){
  return this.illnesses.filter(illness => illness.symptoms.includes(searchString))
}

答案 1 :(得分:0)

尝试使用some方法,该方法将告诉您数组的任何项目是否适合谓词:

如果您想要包含包含传入的searchString症状的任何cause的整个数组,则可以执行以下操作:

filterCauses(searchString: string) {
  searchString = searchString.toUpperCase();
  return this.illnesses.filter((i) => i.symptoms.some((s) => s.toUpperCase()
      .includes(searchString)));
}

更新1:

如果您只想找到可能的原因:

filterCauses(searchString: string): string[] {
  searchString = searchString.toUpperCase();
  return this.illnesses.filter((i) => i.symptoms.some((s) => s.toUpperCase()
      .includes(searchString))).map((i) => i.cause);
}

更新2 :(在评论中提出)

如果您只想要可能的症状:

filterCauses(searchString: string): string[] {
  searchString = searchString.toUpperCase();
  const symptomSet: Set<string> = new Set<string>();
  this.illnesses.forEach((i) => {
    i.symptoms.forEach((s) => {
      if(s.toUpperCase().includes(searchString)) {
        symptomSet.add(s);
      }
    }
  }

  return Array.from(symptomSet.values());
}

更新3 :(在评论中提出)

// @return comma separated list of matching symptoms
filterCauses(searchString: string): string {
  searchString = searchString.toUpperCase();
  const symptomSet: Set<string> = new Set<string>();
  this.illnesses.forEach((i) => {
    i.symptoms.forEach((s) => {
      if(s.toUpperCase().includes(searchString)) {
        symptomSet.add(s);
      }
    }
  }

  return Array.from(symptomSet.values())
           .reduce((acc:string,a:string) => acc += (acc ? ', ' : '') + a,'');
}