What is the best way to eliminate duplicate names from an array?

In my .ts file, I have the following code snippet:

  search(event) {
    this.autocompletedata.filter((entry) => {
        console.log('entryyyy',entry);
        if (this.showFilter == 1) {
            this.results = entry['items'].filter( a => a['item'] ? a['item'].startsWith(event.query) : false);
        }
        else if (this.showFilter == 2) {
            this.results = entry['items'].filter( a => a['service'] ? a['service'].startsWith(event.query) : false);
        } 
        else if (this.showFilter == 3){
            this.results = entry['items'].filter( a => a['phoneNum'] ? a['phoneNum'].startsWith(event.query) : false);
        }

    });
}

The issue I'm facing is that I am receiving duplicated data. Any suggestions on how to remove duplicates from the array?

Below is my full autocomplete code.

This is the structure of the items:

https://i.sstatic.net/boLP1.png

In the last 'if' statement, the results are displayed as suggestions. However, since the array contains multiple instances of the same number, I see repeated suggestions which I want to eliminate. I only want one instance to be displayed.

Answer №1

Here is a sample code snippet to address the issue mentioned. It looks like you are applying a filter for inner items but not for the original array itself, which contains the values:

  this.result  = this.autocompletedata.filter((entry) => {
        if (this.showFilter == 1) {
            entry['item'] = entry['items'].filter( a => a['item'] ? a['item'].startsWith(event.query) : false);
            return true;
        }
        return false;
  });

Answer №2

To eliminate duplicate items from an array, you can make use of the array.filter function as demonstrated below:

// Array containing duplicate names
autocompletedata: Array<string> = ['a','b','v','c','p','a','b']; // For example
output: Array<string> = []; // this array will store filtered non-duplicate items

let names: string = '';
this.output = this.autocompletedata.filter((item, index) => {
    var flag =  names.indexOf(item)===-1; // check if the item is already present or not
    names = index === this.autocompletedata.length-1? '': `${names}${item}`; // create a string of items to compare for duplicates
    return flag; // return true if the item is not a duplicate
})

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

Issues with Angular Material animations may arise following the implementation of a custom theme

Recently, I made the switch to a custom theme in Angular Material version 7 and Angular version 7. Everything seems to be working fine except for the animations - specifically, the mat-progress-bar is no longer moving as expected. This is the code for my ...

utilizing ngfor to iterate through an array of objects within angular

Just diving into Angular, so please bear with me if this question seems basic or if I'm not explaining it clearly. I've set up a component with an input property named satellites that references an array of Satellite objects. I'm trying to ...

Customizing hover color with tailwind CSS

How can I change the color of an icon on mouseover using Tailwind CSS? I have tried to go from this https://i.sstatic.net/ObW6C.png to this https://i.sstatic.net/Tagp3.png, but it's not working. .btn { @apply agt-h-10 agt-w-10 agt-bg-zinc-100 agt- ...

Sass fails to import the theme for the angular material checkbox

I'm facing an issue where, despite specifying imports in my SCSS file and setting up a custom theme, the checkbox styles are not visible except for those related to typography. This is what my SCSS file looks like: @import "~bootstrap/scss/bootstrap ...

Guide on setting up staticfile_buildpack header configuration for an Angular application

After creating a build with ng build --prod, the dist/AppName folder was generated. Inside this folder, I found my manifest.yml and Staticfile. When I tried to do a cf push within the dist/AppName directory, everything worked as expected. However, I want ...

Executing a sibling component's function in React – the ultimate guide!

I am relatively new to the front-end development world and struggling with triggering a function from a sibling component. Let's consider that I have 2 components in App.js. The layout is shown below: https://i.sstatic.net/3C4Av.png function App() { ...

Incorporating Angular, Angular UI, and Typescript while using the "controller as" approach

I'm having trouble with the combination in the topic, there must be a minor mistake somewhere that's causing this issue. Controller: class JobCtrl { job: Object; public $inject = ['$log', '$resource', &apos ...

Angular 14 now offers ngx-pinch-zoom for an enhanced zooming experience

Is it possible to add ngx-pinch-zoom to an Angular 14 project? I encountered a peer dependency conflict when trying to install pinch-zoom with --legacy-peer-deps, which worked in the project but failed in the ci/cd pipeline due to the conflict. I attempt ...

What is the best way to add CSS classes to a different component in AngularDart?

Imagine a straightforward framework for displaying popups: @Component( selector: 'popup-host', template: ''' <div class="popup-container"> <ng-template #popupRef></ng-template> </div> ...

What methods can I use to locate the circular dependency within my program?

I am facing numerous circular dependency errors in my Angular project, causing it to malfunction. Is there a way to identify the section of the code where these circular dependencies exist? Warning: Circular dependency detected: src\app&bs ...

Error in TypeScript due to object being undefined

Exploring TypeScript and facing a challenge with setting properties in an Angular component. When I attempt to define properties on an object, I encounter an error message: ERROR TypeError: Cannot set property 'ooyalaId' of undefined Here is ho ...

Develop a Protractor-based E2E Angular application specifically optimized for slow 3G network connections

Seeking help: I am currently facing a challenge in simulating slow network connections for my e2e tests using Protractor. My project involves angular-cli and angular5. Despite my efforts, I have been unable to find a successful way to mimic slow network s ...

Modifying text input in Angular

I am working on an Angular form that includes a text input which I would like to be able to edit by clicking on the edit button. Within the form, there are 3 buttons available: edit, cancel (which discards changes), and save (which saves changes). When t ...

Leveraging string interpolation within innerHTML in an Angular application

I'm in the process of creating a game where players need to fill in blanks within dynamically generated statements. To achieve this, I require string interpolation to capture user input and dynamic innerHTML as the blanks can be positioned anywhere wi ...

Warning from Firebase CLI deployment: The Node.js 8 runtime has been marked as deprecated and is scheduled to be phased out by 2020-12-05

Attempting to deploy TypeScript onto my FCF isn't working as expected based on the documentation and official Firecasts video. When deploying the default code (helloworld) instead of TypeScript, it deploys a node.js file which is confusing. Below are ...

Tips for sending an object to a specialized child component in ReactJS with Typescript

Purpose I am trying to retrieve data in the root component of my app using useEffect() (and then set it to state) and then pass that state to a custom component. I have successfully accomplished this with JavaScript but seem to be encountering issues when ...

Adjust the font color of the progress bar dynamically based on the background color using SCSS and HTML

I am currently working on a progress bar that displays the percentage of delivery completed. While I have successfully designed the progress bar itself, I am struggling to change the text font color based on the background color of the bar. <div class=& ...

When attempting to Dockerize an Angular CLI app, nothing seemed to happen

I attempted to dockerize my Angular application and created a Dockerfile as follows: FROM teracy/angular-cli as angular-built WORKDIR /usr/src/app COPY package.json package.json RUN npm install COPY . . RUN ng build FROM nginx:alpine LABEL author="pleijan ...

Error message (node:15976): Attempting to establish connection with mongodb resulted in an UnhandledPromiseRejectionWarning

I'm having trouble connecting to MongoDB and I keep getting an error related to async functions. Any idea why this is happening? https://i.sstatic.net/Ce4he.jpg Additionally, when I try to execute npm run start, I encounter the following error: htt ...

Oops! There seems to be an issue where the 'title' property is being accessed from an undefined source

I've been struggling with this code block for the past few days, and even when attempting to initialize it as an object, I encounter errors. Here is my restaurantForm.ts file import { Component, OnInit } from '@angular/core'; import {Rest ...