我有两个数组:
public favoriteTeams: any[] = [
{ name: 'Team Batman' },
{ name: 'Team Superman' },
{ name: 'Team Darkseid' },
{ name: 'Team Wonder Woman' }
];
public searchTeams: any[] = [
{ name: 'Team Iron Man' },
{ name: 'Team Spider Man' },
{ name: 'Team Ant Man' },
{ name: 'Team War Machine' },
{ name: 'Team Batman' },
{ name: 'Team Thor' }
];
我想在两个数组中找到重复的项目,并使用.filter
方法从一个数组中删除重复的值。
目前我的过滤仅搜索初始数组,但不检查另一个数组以查看它是否具有找到的值以便删除它们。
public filterSearchTeams(name: string) {
return this.searchTeams
.filter(team => team.name.toLowerCase().indexOf(name.toLowerCase()) === 0);
}
更新:原始课程:
import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';
@Component({
selector: 'dev-team-chooser',
templateUrl: './dev-team-chooser.component.html',
styleUrls: ['./dev-team-chooser.component.css']
})
export class DevTeamChooserComponent {
public favoriteTeamCtrl: FormControl;
public searchTeamCtrl: FormControl;
public foundTeams: Observable<any[]>;
public favoriteTeams: any[] = [
{name: 'Team Batman'},
{name: 'Team Superman'},
{name: 'Team Darkseid'},
{name: 'Team Wonder Woman'}
];
public searchTeams: any[] = [
{name: 'Team Iron Man'},
{name: 'Team Spider Man'},
{name: 'Team Ant Man'},
{name: 'Team War Machine'},
{name: 'Team Batman'},
{name: 'Team Thor'}
];
constructor() {
this.favoriteTeamCtrl = new FormControl();
this.searchTeamCtrl = new FormControl();
this.foundTeams = this.searchTeamCtrl.valueChanges
.map(team => team ? this.filterSearchTeams(team) : this.searchTeams.slice());
}
public filterSearchTeams(name: string) {
return this.searchTeams
.filter(team => team.name.toLowerCase().indexOf(name.toLowerCase()) === 0)
.filter(val => !this.favoriteTeams.includes(val));
}
}
答案 0 :(得分:0)
如果有人对此结果感兴趣,那就是解决方案:
public filterSearchTeams(name: string) {
return this.searchTeams
.filter(team => team.name.toLowerCase().startsWith(name.toLowerCase()))
.filter(team => !this.favoriteTeams.map(favTeam => favTeam.name).includes(team.name));
}