如何从列表中删除重复项有一些条件,underscore.js?

时间:2015-01-04 13:43:28

标签: javascript underscore.js

我尝试通过电子邮件删除重复的对象,但有一些条件。

考虑我有以下对象列表:

var contacts = [{
    "email": {
        "value": "email1@gmail.com"
      }
  },
  {
    "displayName": "name 1",
    "email": {
        "value": "email1@gmail.com"
      }
  }
]; 

我有600个项目,我想删除所有重复如果我有2个项目使用相同的电子邮件但是在一个项目中我有displayName而在其他没有这样的字段 - >将项目保留为displayName

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

这是Fiddle我玩

请帮忙,

2 个答案:

答案 0 :(得分: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: 'email1@gmail.com' } } ]

它首先根据email.value对所有联系人进行分组,然后仅选择键值对分组的values。然后,它根据它们具有displayName属性的事实对每个组进行分区。如果当前组有它,则从第一个分区返回第一个项目,否则从第二个分区返回。

答案 1 :(得分:0)

避免分区中的整个扫描的另一种方法:

var contacts = [{
    "email": {
        "value": "email1@gmail.com"
      }
  },
  {
    "displayName": "name 1",
    "email": {
        "value": "email1@gmail.com"
      }
  },
  {
    "displayName": "name 2",
    "email": {
        "value": "email2@gmail.com"
      }
  }
];

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": "email1@gmail.com"
//     }
//   },
//   {
//     "displayName": "name 2",
//     "email": {
//       "value": "email2@gmail.com"
//     }
//   }