繁体   English   中英

删除数组对象中的重复项

[英]Removing duplicates in a array object

我有一个数组对象,如下所示:

细节 :

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

我要删除最后一个对象,因为“ Desc”具有与第一个条目重复的条目。

我在javascript中尝试了这种方法,

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

我想要输出,以删除重复项,因此调整数组大小。

细节 :

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

我可以在逻辑上进行哪些修改?

您可以使用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>'); 

尝试这个:

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

使用loadash

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

暂无
暂无

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

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