0

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?

Seabizkit
  • 2,417
  • 2
  • 15
  • 32
user1907849
  • 960
  • 4
  • 19
  • 42
  • Possible duplicate of [Compare a Dynamic ArrayList with ArrayList! and remove the elements which are not present in Dynamic array](http://stackoverflow.com/questions/31378088/compare-a-dynamic-arraylist-with-arraylist-and-remove-the-elements-which-are-no) – Praneeth Apr 15 '16 at 09:00
  • Possible duplicate [Remove duplicate object in array](http://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript) – Jairo Malanay Apr 15 '16 at 09:09

3 Answers3

3

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>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Try this:

var modified = details.filter(function (item) {
    return !details.some(function (item_) {
        return item_ !== item && item_.Desc === item.Desc;
    });
});
karaxuna
  • 26,752
  • 13
  • 82
  • 117
0

Using loadash

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

Devank
  • 159
  • 2
  • 9