Search code examples
angularangular-pipe

Angular Pipe to Hide Duplicates from Array


I want to create a pipe to check specific object, not all. This Pipe will have to hide duplicate.

Pipe

import { Pipe } from '@angular/core'
@Pipe({
    name: 'removeduplicates'
})
export class RemovePipe {

}

Template

<tbody *ngFor="let dt of ash let i = index | removeduplicates: " >
    <tr>
        <td class="tg-yw4l nobord"  style="border-left:  inset;border-right:  none;">{{dt.values}}</td>          
        </tr>
    <tr>            
        <td>{{dt.value2}}</td>
    </tr>
</tbody>

Solution

  • on your component please add a function to remove duplicates

    result:any=[];
    removeDupliacate(){
       this.ash.forEach(function(item) {
            if(this.result.indexOf(item) < 0) {
                this.result.push(item);
            }
       });
    } 
    

    and then in your template

    <tbody *ngFor="let dt of result;let i = index" >
        <tr>
            <td class="tg-yw4l nobord"  style="border-left:  inset;border-right:  none;">{{dt.values}}</td>          
            </tr>
        <tr>            
            <td>{{dt.value2}}</td>
        </tr>
    </tbody>
    

    or you can implement pipe with the help of lodash by installing

    $ npm install --save lodash
    

    this link may help you to install and use lodash

    in your component:

    import { Pipe, PipeTransform } from '@angular/core';
    import * as _ from 'lodash'; 
    @Pipe({
        name: 'removeduplicates'
    })
    export class RemovePipe implements PipeTransform{
       transform(value: any): any{
            if(value!== undefined && value!== null){
                return _.uniqBy(value, 'name');
            }
            return value;
        }
    }
    

    and in your template

    <tbody *ngFor="let dt of ash let i = index | removeduplicates" >
        <tr>
            <td class="tg-yw4l nobord"  style="border-left:  inset;border-right:  none;">{{dt.values}}</td>          
            </tr>
        <tr>            
            <td>{{dt.value2}}</td>
        </tr>
    </tbody>