【问题标题】:Return objects with duplicate properties to a new array [duplicate]将具有重复属性的对象返回到新数组 [重复]
【发布时间】:2021-01-28 03:35:13
【问题描述】:

我已经看到了很多示例,这些示例展示了如何从数组中过滤/删除重复值,但我想获取重复项并在新数组中使用它们。所以对于

array = [
    { id: '1', description: 'foo'},
    { id: '2', description: 'bar'},
    { id: '3', description: 'bloop'},
    { id: '1', description: 'bleep'}
]

我想要返回一个新数组,它只包含具有匹配 ID 的项目

[
  { id: '1', description: 'foo'},
  { id: '1', description: 'bleep'}
]

我觉得这应该比我做的容易

编辑:这些建议不符合我的要求。他们要么创建查找表,要么从原始数组中删除项目。

【问题讨论】:

  • Id方程对你来说足够了吗?
  • 这些解决方案都不符合我的要求
  • @ChristopherMellor 您声称您的问题与建议的副本大不相同。 (即接受的答案只是创建一个“查找表”。)但是,您在这里接受的答案在功能上与那里接受的答案相同。

标签: javascript


【解决方案1】:

array = [
    { id: '1', description: 'foo'},
    { id: '2', description: 'bar'},
    { id: '3', description: 'bloop'},
    { id: '1', description: 'bleep'}
]

const duplicates = array.reduce((a, e) => {
  a[e.id] = ++a[e.id] || 0;
  return a;
}, {});

console.log(array.filter(e => duplicates[e.id]));

【讨论】:

    猜你喜欢
    • 2020-03-04
    • 1970-01-01
    • 2017-03-13
    • 2015-12-14
    • 1970-01-01
    • 2021-10-24
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多