2015-01-04 41 views
2

我嘗試通過電子郵件刪除重複的對象,但有一些條件。如何從列表中刪除重複條件,underscore.js?

考慮我有以下對象的名單:

var contacts = [{ 
    "email": { 
     "value": "[email protected]" 
     } 
    }, 
    { 
    "displayName": "name 1", 
    "email": { 
     "value": "[email protected]" 
     } 
    } 
]; 

我有600個項目,我想刪除所有重複,如果我有例如2項使用相同的電子郵件,但在一個項目我有displayName等在其他沒有這樣的領域 - >離開項目displayName

contacts = _.unique(contacts, function(contact){ 
    return contact.email.value; 
}); 

這是一個Fiddle

玩請幫幫忙,

+0

如果有三個項目,其中兩個有'displayName'? – thefourtheye 2015-01-04 13:44:24

+0

@ thefourtheye以名字取第一名。謝謝 – Snaggs 2015-01-04 13:55:24

回答

2

既然你標記下劃線,我給你只用功能的解決方案。

console.log(_.chain(contacts) 
    .groupBy(function(contact) { 
     return contact.email.value; 
    }) 
    .values() 
    .map(function(contacts) { 
     var parts = _.partition(contacts, _.partial(_.has, _, 'displayName')); 
     return parts[parts[0].length ? 0 : 1][0]; 
    }) 
    .value() 
); 
# [ { displayName: 'name 1', email: { value: '[email protected]' } } ] 

它首先組的所有聯繫人基於所述email.value,然後將其僅挑選鍵值對分組的values。然後根據它們是否具有displayName屬性來劃分每個組。如果當前組擁有它,則從第一個分區返回第一個項目,否則從第二個分區返回。

0

的另一種方式,其避免整個掃描中分區

var contacts = [{ 
    "email": { 
     "value": "[email protected]" 
     } 
    }, 
    { 
    "displayName": "name 1", 
    "email": { 
     "value": "[email protected]" 
     } 
    }, 
    { 
    "displayName": "name 2", 
    "email": { 
     "value": "[email protected]" 
     } 
    } 
]; 

var filteredContacts = 
    _.chain(contacts) 
    .groupBy(// group contacts by email 
     function(contact) { return contact.email.value; } 
    ) 
    .values() 
    .map(
     function(email_contacts) { 
      return _.find(// find the first contact with the *displayName* property... 
       email_contacts, 
       function(contact) { return contact.displayName; } 
      ) || email_contacts[0] // ... or return the first contact 
     } 
    ) 
    .value(); 

// returns 
// [ 
// { 
//  "displayName": "name 1", 
//  "email": { 
//  "value": "[email protected]" 
//  } 
// }, 
// { 
//  "displayName": "name 2", 
//  "email": { 
//  "value": "[email protected]" 
//  } 
// } 
+0

我沒有足夠的代表,病得很厲害 – Snaggs 2015-01-04 18:04:01