简体   繁体   中英

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.

I tried this approach in 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.

 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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