从其他数组删除数组过滤器中的记录

时间:2018-08-09 09:18:32

标签: javascript arrays

我对数组过滤有疑问。

假设我有两个数组:

var names = ["john", "sarah", "dennis"];
var emails = ["john.doe@gmail.com", "william.iron@gmail.com", "bruce.lee@example.com"];

现在哇,如果名称出现在电子邮件中,我可以比较这些数据并删除它吗?

因此,我应该得到第三个数组,而没有 john.doe@gmail.com

var results = ["william.iron@gmail.com","bruce.lee@example.com"];

感谢帮助。

5 个答案:

答案 0 :(得分:2)

您可以过滤emails并检查names电子邮件中是否包含姓名。

var names = ["john", "sarah", "dennis"],
    emails = ["john.doe@gmail.com", "william.iron@gmail.com", "bruce.lee@example.com"],
    result = emails.filter(email => !names.some(name => email.includes(name)));

console.log(result);

使用正则表达式进行检查的另一种方法。

var names = ["john", "sarah", "dennis"],
    regexp = new RegExp(names.join('|'), 'i'),
    emails = ["john.doe@gmail.com", "william.iron@gmail.com", "bruce.lee@example.com"],
    result = emails.filter(email => !regexp.test(email));

console.log(result);

答案 1 :(得分:1)

您可以尝试使用filter

var names = ["john", "sarah", "dennis"];
var emails = ["john.doe@gmail.com", "william.iron@gmail.com", "bruce.lee@example.com"];

var result = emails.filter(email => !names.find(name => email.includes(name)));

console.log(result);

答案 2 :(得分:1)

您可以结合使用Array.filter()Array.find()

var names = ["john", "sarah", "dennis"];
var emails = ["john.doe@gmail.com", "william.iron@gmail.com", "bruce.lee@example.com"];
var res = emails.filter(email => !names.find(name => email.includes(name)));
console.log(res);

如果您还担心IE浏览器,请使用简单的函数声明,而不要使用includes(),而应使用indexOf()

var names = ["john", "sarah", "dennis"];
var emails = ["john.doe@gmail.com", "william.iron@gmail.com", "bruce.lee@example.com"];
var res = emails.filter(function(email) {
  return !names.find(function(name) {
     return (email.indexOf(name) !== -1);
  });
})
console.log(res);

答案 3 :(得分:1)

使用array.prototype.filterarray.prototype.somestring.prototype.includes

var names = ["john", "sarah", "dennis"];
var emails = ["john.doe@gmail.com", "william.iron@gmail.com", "bruce.lee@example.com"];
var res = emails.filter(email => !names.some(name => email.includes(name)));

console.log(res);

答案 4 :(得分:0)

您可以尝试

var names = ["john", "sarah", "dennis"];
var emails = ["john.doe@gmail.com", "william.iron@gmail.com", "bruce.lee@example.com"];

const result = emails.filter(email => { 
  let nameInMail = true
  
  names.forEach(name => {
    if (!nameInMail) {
      return
    }

    nameInMail = !(email.indexOf(name) >= 0)  
  })
  
  return nameInMail
})

console.log(result)

编辑:其他人的回答比我的还好哈哈 使用.some()看起来是最好的方法