我想使用javascript数组过滤电子邮件

时间:2018-07-10 11:07:50

标签: javascript html

我已经基于电子邮件过滤了数组,但是我希望电子邮件一个接一个地显示,以及其他没有gmail,hotmail,yahoo的电子邮件,因为域必须存储在表的其他部分,请如何解决此问题帮助我解决。 我的代码如下:

let  emails = [
    "albert.eisntein@gmail.com", "leonardo_da_vinci@hotmail.com", "jagadish_chandra_bose@yahoo.com", "alan_turing@yahoo.com", "srinivasa.ramanujan@gmail.com", "bjarne_stroustrup@yahoo.com", "max.planck@gmail.com", "nikola.tesla@hotmail.com", "galileo_galilei@hotmail.com", "a.p.j.abdul.kalam@gmail.com", "richard.stallman@inbox.com", "john_von_neumann@mail.com", "c_v_raman@yahoo.com", "isaac.newton@yandex.com", "s_chandrashekar@hotmail.com", "james_gosling@shortmail.com", "ken.thompson@gmail.com", "stephen_hawking@rediffmail.com", "marie_curie@yahoo.com", "michael.faraday@hotmail.com", "charles.babbage@hotmail.com" 
  ],
  filteredEmails = {};;


emails.forEach((el) => {
  let domain = el.split('@')[1];
  if (filteredEmails.hasOwnProperty(domain)) {
     filteredEmails[domain].push(el);
  } else {
    filteredEmails[domain] = [el];
  }
});
document.write("<tr><td>"+ filteredEmails['gmail.com']+ "</td>");
document.write("<td>"+ filteredEmails['hotmail.com'] + "</td>");
document.write("<td>"+ filteredEmails['yahoo.com'] + "</td>");
document.write("<td>"+ filteredEmails['others']+ "</td></tr>");
<h1>Table of Emails</h1>
<table border="1">
<th>Gmail</th>
<th>Hotmail</th>
<th>Yahoo</th>
<th>Others</th>
</table>

1 个答案:

答案 0 :(得分:0)

尝试这样

let  emails = [
    "albert.eisntein@gmail.com", "leonardo_da_vinci@hotmail.com", "jagadish_chandra_bose@yahoo.com", "alan_turing@yahoo.com", "srinivasa.ramanujan@gmail.com", "bjarne_stroustrup@yahoo.com", "max.planck@gmail.com", "nikola.tesla@hotmail.com", "galileo_galilei@hotmail.com", "a.p.j.abdul.kalam@gmail.com", "richard.stallman@inbox.com", "john_von_neumann@mail.com", "c_v_raman@yahoo.com", "isaac.newton@yandex.com", "s_chandrashekar@hotmail.com", "james_gosling@shortmail.com", "ken.thompson@gmail.com", "stephen_hawking@rediffmail.com", "marie_curie@yahoo.com", "michael.faraday@hotmail.com", "charles.babbage@hotmail.com" 
  ],
  filteredEmails = {};;


emails.forEach((el) => {
  let domain = el.split('@')[1];
  if (filteredEmails.hasOwnProperty(domain)) {
     
     if( domain.match( /gmail\.com|hotmail\.com|yahoo\.com/ ) ) {
      filteredEmails[domain].push(el);
    } else {
    filteredEmails['others'].push(el);
    }
     
  } else {
    if( domain.match( /gmail\.com|hotmail\.com|yahoo\.com/ ) ) {
      filteredEmails[domain] = [el];
    } else {
    filteredEmails['others'] = [el];
    }
  }
});

document.write("<tr><td>"+ filteredEmails['gmail.com']+ "</td>");
document.write("<td>"+ filteredEmails['hotmail.com'] + "</td>");
document.write("<td>"+ filteredEmails['yahoo.com'] + "</td>");
document.write("<td>"+ filteredEmails['others']+ "</td></tr>");
<h1>Table of Emails</h1>
<table border="1">
<th>Gmail</th>
<th>Hotmail</th>
<th>Yahoo</th>
<th>Others</th>
</table>