【问题标题】:Find an array that have only the not same object [duplicate]找到一个只有不同对象的数组[重复]
【发布时间】:2019-11-17 21:22:33
【问题描述】:

我有一个数组:

var objArray = [
   { id: 0, name: ‘Object 0’, otherProp: ‘321’ },
   { id: 1, name: ‘O1’, otherProp: ‘648’ },
   { id: 2, name: ‘Another Object’, otherProp: ‘850’ },
   { id: 3, name: ‘Almost There’, otherProp: ‘046’ },
   { id: 4, name: ‘Last Obj’, otherProp: ‘984’ },
   { id: 0, name: ‘Object 0’, otherProp: ‘321’ }
];

这里 id 0 添加两次。我只想要一个没有相同对象的数组。

预期输出:

a = [
   { id: 0, name: ‘Object 0’, otherProp: ‘321’ },
   { id: 1, name: ‘O1’, otherProp: ‘648’ },
   { id: 2, name: ‘Another Object’, otherProp: ‘850’ },
   { id: 3, name: ‘Almost There’, otherProp: ‘046’ },
   { id: 4, name: ‘Last Obj’, otherProp: ‘984’ }] 

如何在 JavaScript 中做到这一点。

【问题讨论】:

  • 请同时添加预期的输出。
  • 如果使用了重复的ID会发生什么?不要插入条目?删除之前的条目?
  • 您正在考虑仅使用id 重复?
  • George Bailey 这仅适用于字符串而不适用于对象
  • @Alexander 然而,通过比较你想认为是唯一的属性(在这种情况下为id)而不是项目本身来调整任意对象的代码是微不足道的。当最终逻辑相同时,我们不需要针对每种不同的情况提出不同的问题。

标签: javascript arrays


【解决方案1】:

您可以通过在Set 中查找id 来过滤数组。

var array = [{ id: 0, name: 'Object 0', otherProp: '321' }, { id: 1, name: 'O1', otherProp: '648' }, { id: 2, name: 'Another Object', otherProp: '850' }, { id: 3, name: 'Almost There', otherProp: '046' }, { id: 4, name: 'Last Obj', otherProp: '984' }, { id: 0, name: 'Object 0', otherProp: '321' }],
    seen = new Set,
    result = array.filter(({ id }) => !seen.has(id) && seen.add(id));

console.log(result);

【讨论】:

  • 感谢 Nina Scholz :) 它正在工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 2015-02-16
  • 2012-12-17
  • 2015-12-07
  • 1970-01-01
  • 2022-01-16
相关资源
最近更新 更多