我正在尝试在此场景的另一个症状中过滤数组。
我的数据和代码如下:
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)
}
}
)
}
答案 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)));
}
如果您只想找到可能的原因:
filterCauses(searchString: string): string[] {
searchString = searchString.toUpperCase();
return this.illnesses.filter((i) => i.symptoms.some((s) => s.toUpperCase()
.includes(searchString))).map((i) => i.cause);
}
如果您只想要可能的症状:
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());
}
// @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,'');
}