Home » Javascript » JS: Compare two Arrays and Remove Duplicate Values from one array by using search filter

JS: Compare two Arrays and Remove Duplicate Values from one array by using search filter

Posted by: admin November 1, 2017 Leave a comment

Questions:

I have two arrays:

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' }
];

I want to find duplicate items in both arrays and remove the duplicate value from one array by using .filter method.

Currently my filtering only searches in the initial array, but doesn’t check another array to see if it has the found values in order to remove them.

public filterSearchTeams(name: string) {
  return this.searchTeams
    .filter(team => team.name.toLowerCase().indexOf(name.toLowerCase()) === 0);
}

Update: original class:

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));
  }

}
Answers:

If somebody is interested in the end this was the solution:

  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));
  }