Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Pipe to remove doubles

Tags:

angular

pipe

I have drop down menu that lists all the country codes of the customer. At the moment I have the problem that I have a lot of double entries, that is if I have three customers from India my dropdown will show IN, IN , IN instead of just one time. I thought I could fix this with the help of a pipe but am blanking how to implement it.

below is my pipe (which is empty because I can't figure out the code):

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'duplicates'
})
export class DuplicatesPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    
    return value;


  }

}

and here my html drop down:

  <strong class="ml-2">Country</strong>
     <select class="ml-1" name="countryCode" [(ngModel)]="countryCode" (change)="gender = ''" (change)="activeStatus = ''">
  <option></option>
  <option *ngFor="let customer of customerArray">{{customer.countryCode | duplicates}}</option>
 </select>
like image 516
kontenurban Avatar asked Mar 04 '23 21:03

kontenurban


2 Answers

you must apply the pipe to the array you are iterating over.

e.g. something like this:

@Pipe({ name: "uniqueCountryCodes" })
export class UniqueCountryCodesPipe implements PipeTransform {

  transform(customers: Customer[], args?: any): any { 
    return customers.map(c => c.countryCode).filter((code, currentIndex, allCodes) => allCodes.indexOf(code) === currentIndex);
  }

}

usage:

<option *ngFor="let code of (customerArray | uniqueCountryCodes)">{{ code }}</option>

keep im mind that as long the pipe is not impure, it filters only once and won't update the countrycodes when a new customer is added to the customerArray.

like image 147
A.Winnen Avatar answered Mar 16 '23 19:03

A.Winnen


You don't need pipe here, you can just remove duplicates from the customerArray itself before binding.

let filteredCustomerArray = [];
this.customerArray.filter(cust=>filteredCustomerArray.indexOf(cust.countryCode) === -1 &&
filteredCustomerArray.push(cust.countryCode));

now do ngFor over this array.

like image 34
Sajeetharan Avatar answered Mar 16 '23 18:03

Sajeetharan