【问题标题】:Remove duplicate content from array从数组中删除重复的内容
【发布时间】:2018-12-07 10:46:29
【问题描述】:
 "name": [
        {
            "name": "test1"
        },
        {
            "name": "test2"
        },
        {
            "name": "test3"
        },
        {
            "name": "test1"
        },
]

我有上面由 nodejs 创建的。在数组推送期间,我想从列表中删除重复的数组,或者如果单个数组不存在,则只推送名称数组。

我尝试了下面的代码,但它改变了数组。

        var new = [];   
        for (var i =0;i<name.length;i++){
            new['name'] = name[i].name;
        }

【问题讨论】:

  • @SanSolo 没有寻找该帖子中给出的解决方案。
  • 您能说明一下您期望的结果吗?建议链接中的多种过滤方法如何不适用于您的情况?特别是“希望从列表中删除重复的数组” - 帖子中显示的示例中没有“重复的数组”(除非您可以互换使用“数组”和“对象” - 请注意,这不再是问题清除)
  • 重复数组是什么意思?您能否在问题本身中添加示例输出?

标签: arrays node.js sorting


【解决方案1】:

最简单的方法可能是使用Array.prototype.reduce。考虑到您的数据结构,这些方面的内容:

obj.name = Object.values(obj.name.reduce((accumulator, current) => {
  if (!accumulator[current.name]) {
    accumulator[current.name] = current
  }
  return accumulator
}, {}));

reduce 会创建一个对象,该对象具有项目名称之外的键,从而确保您只有唯一的名称。然后我使用Object.values() 将其转换回常规对象数组,就像您的数据样本中一样。

【讨论】:

    【解决方案2】:

    解决方案可以使用 temp Set;

    const tmpSet = new Set();
    someObj.name.filter((o)=>{
       const has = tmpSet.has(o.name);
       tmp.add(o.name);
       return has;
    });
    

    过滤器函数遍历 someObj.name 字段并在您返回“true”时对其进行过滤。因此,您检查它是否存在于 tmp Set 中并将当前值添加到 Set 以跟踪重复项。

    PS:new是js中的保留字;

    【讨论】:

      【解决方案3】:

      应该这样做

      const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
      
      let unique = [...new Set(names)];
      console.log(unique); // 'John', 'Paul', 'George', 'Ringo'
      

      https://wsvincent.com/javascript-remove-duplicates-array/

      【讨论】:

        猜你喜欢
        • 2021-12-06
        • 2020-12-31
        • 2014-11-10
        • 1970-01-01
        • 1970-01-01
        • 2011-06-29
        • 1970-01-01
        • 2019-10-19
        相关资源
        最近更新 更多