我有一个包含对象数组的对象。

obj = {};

obj.arr = new Array();

obj.arr.push({place:"here",name:"stuff"});
obj.arr.push({place:"there",name:"morestuff"});
obj.arr.push({place:"there",name:"morestuff"});

我想知道从数组中删除重复对象的最佳方法是什么。例如,obj.arr将变成。。。

{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}

当前回答

我认为最好的方法是使用reduce和Map对象。这是单线解决方案。

常量数据=[{id:1,名称:“David”},{id:2,名称:“Mark”},{id:2,名称:“Lora”},{id:4,名称:“Tyler”},{id:4,名称:“Donald”},{id:5,名称:“Adrian”},{id:6,姓名:“Michael”}]constuniqueData=[…data.reduce((map,obj)=>map.set(obj.id,obj),new map()).values()];console.log(uniqueData)/*在`map.set(obj.id,obj)中`“obj.id”是键。(别担心。我们将只使用.values()方法获取值)“obj”是整个对象。*/

其他回答

Dang,孩子们,让我们把这件事搞砸,为什么不呢?

让uniqIds={},source=〔{id:‘a’},{id:'b‘},{id:'c‘}、{id:s'b‘},{id:‘a‘};let filtered=source.filter(obj=>!uniqIds[obj.id]&&(uniqIds[obj.id]=true));console.log(已过滤);//预期:[{id:'a'},{id:'b'};

带过滤器的内衬(保留订单)

在数组中查找唯一id。

arr.filter((v,i,a)=>a.findIndex(v2=>(v2.id===v.id))===i)

如果顺序不重要,映射解决方案将更快:使用映射解决方案


多个财产独有(地点和名称)

arr.filter((v,i,a)=>a.findIndex(v2=>['place','name'].every(k=>v2[k] ===v[k]))===i)

所有财产都是唯一的(对于大型阵列来说,这将很慢)

arr.filter((v,i,a)=>a.findIndex(v2=>(JSON.stringify(v2) === JSON.stringify(v)))===i)

通过用findLastIndex替换findIndex来保留最后一次出现。

arr.filter((v,i,a)=>a.findLastIndex(v2=>(v2.place === v.place))===i)
function dupData() {
  var arr = [{ comment: ["a", "a", "bbb", "xyz", "bbb"] }];
  let newData = [];
  comment.forEach(function (val, index) {
    if (comment.indexOf(val, index + 1) > -1) {
      if (newData.indexOf(val) === -1) { newData.push(val) }
    }
  })
}
const uniqueElements = (arr, fn) => arr.reduce((acc, v) => {
    if (!acc.some(x => fn(v, x))) { acc.push(v); }
    return acc;
}, []);

const stuff = [
    {place:"here",name:"stuff"},
    {place:"there",name:"morestuff"},
    {place:"there",name:"morestuff"},
];

const unique = uniqueElements(stuff, (a,b) => a.place === b.place && a.name === b.name );
//console.log( unique );

[{
    "place": "here",
    "name": "stuff"
  },
  {
    "place": "there",
    "name": "morestuff"
}]

使用ES6“reduce”和“find”数组助手方法的简单解决方案

工作效率高,非常好!

"use strict";

var things = new Object();
things.thing = new Array();
things.thing.push({
    place: "here",
    name: "stuff"
});
things.thing.push({
    place: "there",
    name: "morestuff"
});
things.thing.push({
    place: "there",
    name: "morestuff"
});

// the logic is here

function removeDup(something) {
    return something.thing.reduce(function (prev, ele) {
        var found = prev.find(function (fele) {
            return ele.place === fele.place && ele.name === fele.name;
        });
        if (!found) {
            prev.push(ele);
        }
        return prev;
    }, []);
}
console.log(removeDup(things));