从数组中删除重复的内容

时间:2018-12-07 02:35:58

标签: arrays node.js sorting

 "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;
        }

3 个答案:

答案 0 :(得分: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()将其变回对象的常规数组,就像您的数据样本中一样。

答案 1 :(得分:0)

该解决方案可以使用临时设置;

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

过滤器函数遍历someObj.name字段,如果返回“ true”,则将其过滤到位。因此,您要检查tmp设置中是否存在该设置,并将当前值添加到设置中以跟踪重复项。

PS:new是js中的保留字;

答案 2 :(得分:-1)

这应该做

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/

相关问题