-1

I have a requirement to remove repeated objects from an array based on certain condition check If any of the object with same "connector", "address", "type" values in this array i need remove that object.

array =  [{
        connector : 'smtp',
        name : 'john',
        address : 'john@gmail.com',
        type : 'cc'
    }, {
        connector : 'smtp',
        name : 'john',
        address : 'john@gmail.com',
        type : 'cc'
    }, {
        connector : 'gtp',
        name : 'mark',
        address : 'mark@gmail.com',
        type : 'cc'
    }, {
        connector : 'ftp',
        name : 'wiki',
        address : 'wiki@gmail.com',
        type : 'bcc'
    },
    {
        connector : 'smtp',
        name : 'wiki',
        address : 'wiki@gmail.com',
        type : 'cc'
    }
 ]

I need the output like the following way

output = [{
        connector : 'smtp',
        name : 'john',
        address : 'john@gmail.com',
        type : 'cc'
    },{
        connector : 'gtp',
        name : 'mark',
        address : 'mark@gmail.com',
        type : 'cc'
    }, {
        connector : 'ftp',
        name : 'wiki',
        address : 'wiki@gmail.com',
        type : 'bcc'
    },
    {
        connector : 'smtp',
        name : 'wiki',
        address : 'wiki@gmail.com',
        type : 'cc'
    }
 ]

Sorry i tried some repeated foreach looping but ended up no where. Could you help me to find any efficient way of doing the same.

Dibish
  • 9,133
  • 22
  • 64
  • 106

1 Answers1

1

It can be done with the help of underscore uniq.

array =  [{
        connector : 'smtp',
        name : 'john',
        address : 'john@gmail.com',
        type : 'cc'
    }, {
        connector : 'smtp',
        name : 'john',
        address : 'john@gmail.com',
        type : 'cc'
    }, {
        connector : 'gtp',
        name : 'mark',
        address : 'mark@gmail.com',
        type : 'cc'
    }, {
        connector : 'ftp',
        name : 'wiki',
        address : 'wiki@gmail.com',
        type : 'bcc'
    },
    {
        connector : 'smtp',
        name : 'wiki',
        address : 'wiki@gmail.com',
        type : 'cc'
    }
 ]
 //generating a string of keys you wish to compare which forms the criteria for uniqueness
 add = _.uniq(array, function(a){ return a.connector + "-" + a.address + "-" + a.type;})

 console.log(add)

working code here

Cyril Cherian
  • 32,177
  • 7
  • 46
  • 55