JavaScript: Remove duplicate values from one array by comparing and utilizing a search filter against another array

There are two arrays available:

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

The goal is to identify duplicate items in both arrays and remove the duplicates from one array using the .filter method.

At present, the filtering process only scans through the initial array without cross-checking with another array to eliminate the matching values.

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

Class update:

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

}

Answer №1

For those curious about the resolution, here is the code that solved the issue:

  private filterSearchTeamsByName(nameToFilter: string) {
    return this.searchTeams
      .filter(team => team.name.toLowerCase().startsWith(nameToFilter.toLowerCase()))
      .filter(team => !this.favoriteTeams.map(favTeam => favTeam.name).includes(team.name));
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The response from AJAX is successfully retrieved, however, the HTML code within the response is not being appended to the

html: <form method="POST"> <input type="text" name="input1" id="input1"> <input type="text" name="input2" id="input2"> <button type="button" onclick="checkInputs()">OK</button> </form> <div id="display_panels">< ...

How to include subdirectories in a TypeScript npm module

I am in the process of developing a package for npm and I would like it to be imported in the following manner: import myPackage from 'my-package'; import { subFunction1, subFunction2 } from 'my-package/subfunctions'; Upon trying to u ...

What is the best way to switch a Boolean value in React Native?

Struggling with toggling a Boolean state from true to false when the result is undefined. Tried several methods but none seem to work. The boolean state in the constructor is defined like this: class UserInfo extends Component{ constructor(props){ s ...

Echo command fails to work with location.href

I am facing a small issue with my PHP echo. I have a JavaScript link function that is not working because the HTML code shows this type of link onclick="location.href="http://www.link.com/";". It's clear that this syntax won't work. However, if w ...

Can the JQGrid subgrid URL be modified to change the parameter value from "?Id=id"?

I'm currently working on setting up a JqGrid with a subgrid like this... jQuery(document).ready(function() { jQuery("#list").jqGrid({ url: '/OrganizationalUnit/FindAll/', datatype ...

Creating a new field in a Mongoose schema generates an array that is

Within my Cuisine schema, I have various fields that are determined by another field named delicious. For instance: If delicious is set to sushi, the required fields are rice and fish If delicious is set to tacos, the necessary fields are tortilla, meat ...

What is the syntax for adjusting background-position with ngStyle in Angular 4?

It's finally Friday! I'm a bit confused about how to properly set the background-position-x property in an [ngStyle] directive in Angular 4 with Ionic 3. Can someone guide me on the correct way to implement background-position-x? I expect the ou ...

Guide on adding HTML to an array every third time for displaying

Is there a way to generate div elements every 3 times in a for loop without outputting them as HTML? Any suggestions on how to achieve this? render() { const squareItems = []; for (var i=0; i < 9; i++) { if ((i % 3) == 0){ ...

Customizing individual textareas in tinyMCE can easily be done by adjusting the

This resource provides instructions on customizing features like the menubar and status bar for all form fields within tinyMCE: tinymce.init({ selector: "textarea", menubar:false, statusbar: false, .. }); I am wondering how to achieve th ...

Trouble with window.location functionality following an AJAX request

After a successful response from an AJAX request, the window.location method is not working as expected. However, when I debug step by step in Firefox, the window.location works fine. function login(){ var jason ={"usuario":document.getElementById("inp ...

Ways to prevent a user from reaching a specific page by entering the URL in a react and typescript application

Is there a way to restrict access to a specific page with the URL "myurl/view"? I want only admin users to be able to view this page, while preventing other users from accessing it. Currently, when the view button is clicked, it redirects to the URL "/vie ...

sending an array of information to a shader in a threeJS environment

I am currently working on passing "volume._data" to my fragment shader in threeJS. This data is stored as a Float32Array and has a maximum of 512x512x512x4 elements. var mat = new THREE.ShaderMaterial({ uniforms: { color: {type: &apo ...

Optimizing Performance by Managing Data Loading in JavaScript Frameworks

I am new to JavaScript frameworks like React and Vue, and I have a question about their performance. Do websites built with React or Vue load all data at once? For example, if I have a page with many pictures, are they loaded when the component is used or ...

Utilizing Google chart tools allows you to incorporate multiple charts onto a single page

<html> <head> <script type="text/javascript" src="https://www.google.com/jsapi"> </script> <script type="text/javascript> google.load("visualization", "1", { packages: ["corechart"] }); google.setOnLoa ...

Unable to reposition multiple THREE.Mesh objects in an array due to them being labeled as "read only" and "undefined"

Currently, I am delving into the world of three.js and managed to create a function that generates a 3x3x3 grid made of cubes. let cubes = []; function createGrid3x3(gridMaterial, positionZ) { for( let k = 1; k < 4; k++) { for( let j = 1; j ...

Replace the image source with a list of images

I am looking to create a dynamic image list using either an array or an HTML list. When I hover over an image, it should change one by one with a fade or slide effect, and revert back to the default images when I hover out. Question 1: What type of list s ...

The data structure '{ variableName: string; }' cannot be directly assigned to a variable of type 'string'

When I see this error, it seems to make perfect sense based on what I am reading. However, the reason why I am getting it is still unclear to me. In the following example, myOtherVariable is a string and variableName should be too... Or at least that&apos ...

Ways to reach the Document Object Model in a functional component

While working on a speedometer project in ReactJS with some vanilla syntax, I encountered an issue where the canvas element was returning null. Oddly enough, when running const canvas = document.getElementById('dial__container'); in the console, ...

The query fails to retrieve results for the specified date and the beginning of the month

I have encountered an issue with my query that is supposed to fetch values between the start and end of the month. Interestingly, when a record is entered on the first day of the month, it doesn't get returned in the query result. Only records entered ...

implementing firestore onsnapshotListner feature with pagination

I have a web application that needs real-time updates on a large collection of documents. However, due to the size of the collection, retrieving data without applying a limit is not feasible and inefficient. Therefore, it is crucial to implement a query li ...