简体   繁体   English

删除数组对象中的重复项

[英]Removing duplicates in a array object

I have an array object as follows: 我有一个数组对象,如下所示:

details : 细节 :

Array[2]
>0: Object
    Name:"a"
    Desc:"Desc"
>1: Object
    Name:"b"
    Desc:"Desc2"
>2: Object
    Name:"C"
    Desc:"Desc"

I want to remove the last object since the "Desc" has the duplicate entry with the first entry. 我要删除最后一个对象,因为“ Desc”具有与第一个条目重复的条目。

I tried this approach in javascript, 我在javascript中尝试了这种方法,

removedup = details.reduce(function(a,b) { if (a.indexOf(b) < 0) a.push(b); return a },[]);

I want the output, to remove the duplicates and therefore adjust the array size. 我想要输出,以删除重复项,因此调整数组大小。

details : 细节 :

Array[1]
>0: Object
    Name:"a"
    Desc:"Desc"
>1: Object
    Name:"b"
    Desc:"Desc2"

what can I modify in logic? 我可以在逻辑上进行哪些修改?

You could use Array#filter() and thisArgs for a temporary object. 您可以使用Array#filter()thisArgs作为临时对象。

 var details = [{ Name: 'a', desc: 'Desc' }, { Name: 'b', desc: 'Desc2' }, { Name: 'C', desc: 'Desc' }, {Name: 'a', desc: 'toString'}], removedup = details.filter(function (a) { if (!(a.desc in this)) { this[a.desc] = true; return true; } }, Object.create(null)); document.write('<pre> ' + JSON.stringify(removedup, 0, 4) + '</pre>'); 

Try this: 尝试这个:

var modified = details.filter(function (item) {
    return !details.some(function (item_) {
        return item_ !== item && item_.Desc === item.Desc;
    });
});

Using loadash 使用loadash

var output = _.chain(Array).reverse().indexBy('Desc').toArray().value(); var输出= _.chain(Array).reverse()。indexBy('Desc')。toArray()。value();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM