在打字稿中,我有两个数组:
var StarWarsChars: any = [
"Jedi Yoda",
"Jedi Mace Windu",
"Jedi Qui-Gon Jinn",
"Jedi Qui-Gon Jinn",
"Jedi Obi-Wan Kenobi",
"Sith Count Dooku",
"Sith Darth Sidious",
"Droid R2-D2",
"Droid R2-D2",
"Droid C-3PO",
"Droid BB-8"
];
var StarWarsFilter: any = ["Jedi", "Sith"];
,我希望创建一个由StarWarsChars数组中的值组成的第三个数组,其中值包含StarWarsFilter中的值。我知道如何根据单个值进行过滤:
var StarWarsFiltered = StarWarsChars.filter(e =>
e.includes(StarWarsFilter[0])
);
返回:
0: "Jedi Yoda"
1: "Jedi Mace Windu"
2: "Jedi Qui-Gon Jinn"
3: "Jedi Qui-Gon Jinn"
4: "Jedi Obi-Wan Kenobi"
但是我不知道如何对StarWarsFilter中的所有值执行此过滤器。我可以尝试循环,但我想有一种更好的方法。
答案 0 :(得分:3)
首先,我建议为您的数组使用正确的类型:string[]
您应该能够执行以下操作:
var StarWarsChars: string[] = [
"Jedi Yoda",
"Jedi Mace Windu",
"Jedi Qui-Gon Jinn",
"Jedi Qui-Gon Jinn",
"Jedi Obi-Wan Kenobi",
"Sith Count Dooku",
"Sith Darth Sidious",
"Droid R2-D2",
"Droid R2-D2",
"Droid C-3PO",
"Droid BB-8"
];
var StarWarsFilter: string[] = ["Jedi", "Sith"];
var StarWarsFiltered = StarWarsChars.filter(e =>
StarWarsFilter.some(f => e.includes(f))
);
答案 1 :(得分:0)
const StarWarsFiltered =
StarWarsChars.filter(x => x.split(' ').some(y => StarWarsFilter.includes(y)));
这将返回StarWarsChars中所有在StarWarsFilter中包含单词的项