【问题标题】:How to eliminate duplicate object from a list of arrays of objects如何从对象数组列表中消除重复对象
【发布时间】:2020-10-01 15:48:18
【问题描述】:

我想从数组列表中消除重复的对象

我使用 map 重塑第一个数组“issueComment”,然后使用过滤器删除重复的对象,但它不起作用

const shapeCodes = this.issueComment.map(p => [p.ShapeCode, (this.lang === 'fr') ? 
  p.ShapeDescriptionFrench : p.ShapeDescriptionEnglish,
  p.AdminVCCQuestionnaireInstanceID]).filter((value, index, self) => self.indexOf(value) === index);

控制台输出:

6) [Array(3), Array(3), Array(3), Array(3), Array(3), Array(3)]
0: (3) ["Transit_right_14", "Glace porte passager", 3504406]
1: (3) ["Transit_right_14", "Glace porte passager", 3504406]
2: (3) ["Transit_right_14", "Glace porte passager", 3504406]
3: (3) ["Transit_right_14", "Glace porte passager", 3504406]
4: (3) ["Transit_right_14", "Glace porte passager", 3504406] 
5: (3) ["Transit_right_14", "Glace porte passager", 3504406]

【问题讨论】:

  • 这个问题已经回答了很多次了,不是Typescript问题,而是javascript问题。
  • 我已经看到了对象数组重复的示例,但不是数组列表
  • 数组和对象是通过引用而不是值进行比较的。两个数组字面量总是会创建两个不同的数组,所以[[]].indexOf([]) 总是-1
  • 这能回答你的问题吗? How to compare arrays in JavaScript?

标签: arrays typescript dictionary filter duplicates


【解决方案1】:

对象的问题是它们通过引用进行比较,并且由于每个数组都是唯一的引用,因此在使用=== 时它们不会被视为等效。您必须逐个比较每个元素的等效性。

// below will log out 'false'
const a:number[] = [1];
const b:number[] = [1];
console.log(a === b);

// below will log out `true`
const a:number[] = [1];
const b = a;
console.log(a === b);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-25
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    相关资源
    最近更新 更多