alim1990
alim1990

Reputation: 4972

Angular 2 pipes check if a value already exist in an array

I did this pipe in angular 2 which filters an array according to some criteria:

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

@Pipe({
  name: 'filter',
  pure: false
})
export class FilterPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    if(value.length === null){
        return value;
    }

    let resultArray = [];
    for(let item of value)
    {
        if(item.match('^.*'+args[0]+'.*$'))
        {
            resultArray.push(item);
        }
    }
    return resultArray;
  }

}

And here is the html page where I use the filter to only display the values that start with letter e:

<input type="text" [(ngModel)]="val">
<hr>
<button type="button" class="btn btn-primary" (click)="onClick(val)">Add Item</button>
<hr>
<h1>
  <li *ngFor="let item of values | filter: 'e'">{{item}}</li>
</h1>

The onClick() method is represented by the following script:

export class AppComponent {
  title = 'app works!';
  values=['east', 'middle east'];

  onClick(val)
  {
    // if(val==null)
    // {
    //  return null;
    // }
    // val=this.values.indexOf(values)
    this.values.push(val);

    //this.values.push(val);
    //console.log(val)
  }

I want to add a condition to the filter to see if there is an existing value in the array, even if it starts with letter e, to not add it to the array.

I tried the following in the onClick() method but it didn't worked and no errors were displayed:

onClick(val)
  {
    if(val==null)
    {
        return null;
    }
    else{
        if(val==this.values.indexOf(this.values))
        {
            return null;
        }
        else
        {
            this.values.push(val);
        }
    }

So I added the following in the pipe:

   if(item.match(args[0]))
    {
        return null;
    }

And still didn't worked with no errors.

Upvotes: 0

Views: 4120

Answers (1)

Hristo Eftimov
Hristo Eftimov

Reputation: 15703

In your pipe you can filter the unique elements in your array and remove the duplicates:

let uniqueArray = value.filter(function (el, index, array) { 
    return array.indexOf (el) == index;
});

Then you can catch these elements that start with your specific string:

for (let item of uniqueArray) {
    if (item.match("^"+args[0])) {
        resultArray.push(item);
    }
}

I created a working example: https://plnkr.co/edit/zqhFlTmp5YxABf4LVNUV?p=preview

You can see your real data and the filtered data.

Upvotes: 3

Related Questions