javascript - 在 Angular 8 中查找数组中的所有重复项

标签 javascript typescript

我试图在 Angualar 8 的 attachmentForms 列表中找到所有重复项。我搜索了一些帖子,下面是我可以想出的代码,但我仍然无法设置isDuplicatetrue 名称:Document1。感谢您对此提供的任何帮助。

export interface AttachmentForm {
  name: string;
  isDuplicate: boolean;
}

  ngOnInit() {
    this.attachmentForms = [
      {name: 'Document1', isDuplicate: false},
      {name: 'Document2', isDuplicate: false},
      {name: 'Document1', isDuplicate: false},
      {name: 'Document3', isDuplicate: false},
    ];
   this.findDuplicates() ;
  }
 findDuplicates() {
    const newArr: AttachmentForm[] = [];
    this.attachmentForms.forEach((item, index) => {
      if (newArr.findIndex(i => i.name === item.name) === -1) {
        item.isDuplicate = false;
      } else {
        item.isDuplicate = true;
      }
      newArr.push(item);
    });
    this.attachmentForms = newArr;
  }


最佳答案

尝试将 findDuplicates() 更改为 this.findDuplicates()

ngOnInit() {
    this.attachmentForms = [
        { name: 'Document1', isDuplicate: false },
        { name: 'Document2', isDuplicate: false },
        { name: 'Document1', isDuplicate: false },
        { name: 'Document3', isDuplicate: false },
    ];
    this.findDuplicates();
}

findDuplicates() {
    const newArr: AttachmentForm[] = [];
    this.attachmentForms.forEach((item) => {
        if (this.attachmentForms.filter(i => i.name === item.name).length > 1) {
            item.isDuplicate = true;
        } else {
            item.isDuplicate = false;
        }
        newArr.push(item);
    });
    this.attachmentForms = newArr;
}

这是一个 Stackblitz 示例:https://stackblitz.com/edit/angular-nl8zxc

关于javascript - 在 Angular 8 中查找数组中的所有重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58917445/

相关文章:

javascript - 没有 UI 的 jQuery 嵌套选项卡

javascript - ExtJS Forms > .getFieldValues() 函数不返回 "timefield"xtype 的任何值

javascript - 流量: Cannot assign _ to _ because property _ is missing in _

angular - 在 ionic 搜索栏上输入验证?

typescript - OpenAI GPT-3 API 错误 : "TypeError: openai.completions is not a function"

javascript - 为什么 var name = function(){...} 形式的函数在 ES5 中没有被提升?

javascript - 'x' 未定义 - React map 分派(dispatch)到 Props

javascript - 迭代对象属性

angular - 将多个点击事件映射到一个方法

reactjs - 错误 TS2314 : Generic type 'Component<P, S>' requires 2 type argument(s)