首页 > 解决方案 > 使用 Angular 中的管道过滤器过滤数组中的唯一元素

问题描述

在此处输入图像描述我正在尝试使用 Angular 实现管道。下面是我尝试过的代码。我想检索唯一的完整列表。所以我为内部列表添加了一个管道过滤器名称。但我仍然得到重复的元素。我添加了 json 以供参考。内部 ArticleTags 数组有一个对象列表。同样,每个父数组都有多个 ArticleTags 数组。我想从整个列表 ArticleTags 数组中检索唯一元素。我认为它检索特定内部列表中的唯一元素,而不是从文章标签的整个列表中检索。

在此处输入图像描述

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'filterUnique',
    pure: false
  })
  export class FilterPipe implements PipeTransform {
    transform(value: any, args?: any): any {
      // Remove the duplicate elements
      const uniqueArray = value.filter(function (el, index, array) {
        return array.indexOf (el) === index;
      });
      return uniqueArray;
    }
  }







<ul>
          <li *ngFor="let articlesResult of articlesListArray; let i=index">
            <ul>
              <li  *ngFor="let articlesTagResult of articlesResult.ArticleTags | filterUnique; let j=index">
                <i class="fa fa-times-circle" *ngIf="articlesResult.ArticleTags[j].value"></i>
                <label class="form-check-label" for="exampleCheck" *ngIf="articlesResult.ArticleTags[j].value">{{articlesResult.ArticleTags[j].value}}</label>
              </li>
            </ul>
          </li>
        </ul>


getLatestArticles(currdate): void {
    this.ng4LoadingSpinnerService.show();
    this.ArticlesServiceCall.getArticlesDashboard(currdate)
      .subscribe(
        resultArray => {
          this.ng4LoadingSpinnerService.hide();
          this.articlesList = resultArray;
          this.articlesLists = resultArray.ResponseValue;
          this.articlesListArray = this.articlesLists.slice(0, 8);
        },
        error => console.log('Error :: ' + error)
      );
  }

我从articlesListArray 获取主数组数据并将其传递给html


2018 年 7 月 9 日的编辑更新

使用以下管道代码获取以下错误。

从“@angular/core”导入 { Pipe, PipeTransform };

@Pipe({ name: 'filterduplicates' }) 导出类 FilterduplicatesPipe 实现 PipeTransform {

transform(value: any, args?: any): any {
    // Remove the duplicate elements
    const art = value.map( x => {
        return x.ArticleTags ? x.ArticleTags.map(y => {
            return y.value ? y.value : null;
        }) : [];
    }).reduce((acc, ele, i) => {
        acc = acc.concat(ele);
        return acc;
    }).filter( z => {
        if (z) {
            return z;
        }
    });
    return new Set(art);
}

} 在此处输入图像描述

标签: angularpipe

解决方案


参考这里有独特的过滤器给出了 https://www.npmjs.com/package/ng2-pipes

  ex:   array | unique: 'Property (Optional)'
        this.items = [1, 2, 3, 1, 2, 3];
        <li *ngFor="let item of items | unique"> <!-- Array: [1, 2, 3] -->

推荐阅读