试图从列表中删除不重复的重复项

时间:2015-08-30 22:37:16

标签: javascript

我想打印<textarea>中提供的电子邮件地址的用户名,但没有重复项。

    

<textarea id="emailTextarea" rows ="10" cols="25" >
sara@yahoo.com
adam@yahoo.com
todd@yahoo.com
henry@yahoo.com
wright@yahoo.com
sara@yahoo.com
adam@yahoo.com
todd@yahoo.com
</textarea>

<body onload="emailSort()">

<script>
//email sort function

function emailSort(){

    //get data from the textarea

    var emailList = document.getElementById("emailTextarea").value;

    //put into array
    var emailListArray = emailList.split("\n");

    //remove the extension and duplicates

    var usernamesArray = emailListArray.map(function(val, index, arr) {
            var username = val.slice(0, val.indexOf('yahoo.com'));
        if(!val[username]) val[username] = true;
        return emailUsers;

    });

    //sort the list

    var sortedUsernames = usernamesArray.sort();

    //print out the list

    document.write(sortedUsernames.join('</br>'));
}

3 个答案:

答案 0 :(得分:2)

如果您可以使用lo-dash,请尝试以下操作:

var emails = _.compact(document.getElementById('emailTextarea').value.split("\n"));

console.log('Sorted unique emails', _.uniq(emails).sort());

示例: http://jsfiddle.net/j6cnzpdv/

没有Lodash:

var sortedUniqueEmails = document.getElementById('emailTextarea').value
    // Build array of emails
    .split("\n")

    // Sort
    .sort()

    // Remove invalid/falsy entries (ie. blank lines)
    .filter(function(line) {
        return line.indexOf('@') > -1; // Assuming this is enough to validate an email
    })

    // Remove duplicates
    .reduce(function(result, email) {
      if (result.indexOf(email) < 0) result.push(email);

      return result;
    }, []);

console.log('Sorted unique emails', sortedUniqueEmails);

示例: http://jsfiddle.net/xa2Ltxth/

答案 1 :(得分:0)

这是我的Claudio解决方案的版本,但没有删除,包括删除&#34; @ yahoo.com&#34;:

var uniques = new Set();
emails.split("\n").sort().forEach(function(i){
                uniques.add(i);
});
var uniquesTrimmed = [];
uniques.forEach(function(val){uniquesTrimmed.push(val.slice(0, val.indexOf('@yahoo.com')))});

在此处试试:http://jsfiddle.net/j6cnzpdv/1/

答案 2 :(得分:0)

试试这个例子:

function emailSort() {
  var emails = document.getElementById("emailTextarea").value.split("\n");
  var users = [],  l = emails.length, id;
  while (l--)
    if ((id = emails[l].match(/\w+@/)) && (-1 === users.indexOf(id[0])))
      users.push(id[0]);
  alert(users.sort().join(", "));
}
<body onload="emailSort()">
  <textarea id="emailTextarea" rows ="10" cols="25" >
  sara@yahoo.com
  adam@yahoo.com
  todd@yahoo.com
  henry@yahoo.com
  wright@yahoo.com
  sara@yahoo.com
  adam@yahoo.com
  todd@yahoo.com
  </textarea>
</body>