如何删除自动完成中的重复值?

时间:2018-12-05 10:39:43

标签: angular typescript

我使用“ ng-select”。如何从自动完成中删除重复的值?也就是说,我假设两次在group_operations字段中添加了SPB值,然后如何从下拉列表中删除SPB值以从中自动完成自动完成的列表,是第二次或更多次添加的。

<ng-select [addTag]="true" formControlName="group_operations" id="group_operations">
  <ng-option *ngFor="let sprOperation of sprOperations" [value]="sprOperation.group_operations">{{sprOperation.group_operations}}</ng-option>
</ng-select>

2 个答案:

答案 0 :(得分:2)

使用此方法:

function uniques(array: any[], key: string) {
  return array.reduce((acc, curr) => {
    if (!acc.find(item => item[key] === curr[key])) { acc.push(curr); }
    return acc;
  }, []);
}

在管道,数组原型或组件中。

摘要:

function uniques(array, key) {
  return array.reduce((acc, curr) => {
    if (!acc.find(item => item[key] === curr[key])) { acc.push(curr); }
    return acc;
  }, []);
}

console.log(uniques([
  { id: 1, value: '1' },
  { id: 1, value: '1' },
  { id: 2, value: '2' },
  { id: 3, value: '3' },
], 'id'));

答案 1 :(得分:0)

这是示例代码,可以根据您的数据集进行修改。

export class DataComponent {

  constructor() {
    items: any[];

    // Get all sprOperations
    const operation = items.map(sprOperations=> sprOperations.group_operations);

    // Unique sprOperations
    this.sprOperations= operation.filter((x, i, a) => x && a.indexOf(x) === i);
  }
}
相关问题