I am getting the Response from the server like this

{
    owners:[
    {
    _id:"33333"
    email:[email protected]
    }
    {
    _id:"1111"
    email:[email protected]
    }]
    employee:[
     {
    _id:"44342"
    email:[email protected]
    }
    {
    _id:"35345"
    email:[email protected]
    }
     {
    _id:"3556"
    email:[email protected]
    }
    ]
    users:[
    {
    _id:"56744"
    email:[email protected]
    }
    {
    _id:"8908"
    email:[email protected]
    }]
}

i want keep the objects Which are only having unique email id in all the array of objects the Result should be like this:

{
    owners:[
    {
    _id:"33333"
    email:[email protected]
    }
    {
    _id:"1111"
    email:[email protected]
    }]
    employee:[

    {
    _id:"35345"
    email:[email protected]
    }
     {
    _id:"35345"
    email:[email protected]
    }
    ]
    users:[
    {
    _id:"56744"
    email:[email protected]
    }
]
}

can anybody help me on this Please.

share|improve this question
    
Which of the duplicate records do you want to preserve, the first one? Because the _id's are unique and that inof will be lost forever. – Benny Bottema Jul 21 at 19:45

Since you want uniqueness across two array, you have to combine them first.

let combined = result.owners.map(o => {o.type = 'owner'; return o;})
            .concat(result.users.map(u => {u.type = 'user'; return u;});
combined = _.uniqBy(combined, 'email');

result.owners = _.filter(combined, {type: 'owner');
result.users = _.filter(combined, {type: 'user');

same thing with employees.

share|improve this answer

Well there are a few ways of doing this. One of the easiest would be using libraries like lodash or underscore and using the uniq method to filter out duplicate objects on the basis of a property.

Using underscore as an example to get a unique list of owner objects:

_.uniq(owners, 'email')

Or a function of this sort would also work:

function uniqeValues(objects, property) {
     let unique_values = {};

     objects.forEach(object=> {
         if (!unique_values.hasOwnProperty(object[property])) {
             unique_values[object[property]] = object;
         }
     });

     return Object.values(unique_values);
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.