我删除重复项的功能不起作用,有什么建议吗?

时间:2015-08-28 20:11:01

标签: javascript

<p id="demo"></p>

<script>

//This is the email list

var emailList =["adam@yahoo.edu\n", "henry@yahoo.edu\n", "john@yahoo.edu\n", "sally@yahoo.edu\n", "adam@yahoo.edu\n", "david@yahoo.edu\n", "myhome@yahoo.edu\n", "david@yahoo.edu\n", "david@yahoo.edu\n", "hunger@yahoo.edu\n", "madison@yahoo.edu\n", ];

//I am removing @yahoo.edu

function removeAddress(list){
    for (var i = 0; i < list.length; i++) {
        list[i] = list[i].replace("@yahoo.edu", " ");
    }
}

//Function to remove the duplicates in the list

function removeDuplicates(list)
{
    var hash = {};
    for (var i = 0; i < list.length; i++)
    {
        var array = list[i];
        for (var j = 0; j < array.length; j++) 
        {
            var val = array[j];
            var hashedVal = hash[val];
            if (hashedVal === undefined) 
            {
                hash[val] = true;
            }
            else 
            {
                array.splice(j, 1);
                if (array.length == 0)
                {
                    list.splice(i, 1);
                }
            }
        }
    }
}
document.getElementById("demo").innerHTML = emailList;
//Remove @yahoo.edu from the list

removeAddress(emailList);

//Sort the list

emailList.sort();

//Remove the duplicates

removeDuplicates(emailList);

//Print the list

document.getElementById("demo").innerHTML = emailList;
</script>

</body>
</html>

3 个答案:

答案 0 :(得分:5)

首先,我不确定你为什么要遍历带有2个循环的1维数组。这不是必要的。其次,你在遍历数组的同时也删除了元素。删除元素后,将其后面的所有元素向前推送1个索引。然后i递增,导致您错过一个项目。如果您想继续使用for循环并使用.splice(),则需要在删除项目时手动递减i。此外,您只需要一个循环,因为emailList是一个字符串数组。

function removeDuplicates(list)
{
  var hash = {};
  var newList = [];
  for (var i = 0; i < list.length; i++)
  {
    var email = list[i];
    if (hash[email] === undefined) {
      hash[email] = true;
    } else {
      list.splice(i, 1);
      i --;
    }
  }
}

请参阅http://codepen.io/anon/pen/YyKJOP

答案 1 :(得分:1)

在内部for中,您循环一个字符串,而不是另一个数组。 其次,您可能希望在末尾.join()数组以获取可打印的字符串。

答案 2 :(得分:0)

基本上,你只是得到一个用户名列表。它可以简化为以下内容:

var emailList = ["adam@yahoo.edu\n", "henry@yahoo.edu\n", "john@yahoo.edu\n", "sally@yahoo.edu\n", "adam@yahoo.edu\n", "david@yahoo.edu\n", "myhome@yahoo.edu\n", "david@yahoo.edu\n", "david@yahoo.edu\n", "hunger@yahoo.edu\n", "madison@yahoo.edu\n"];

var usernameHash = emailList.reduce(function(usernames, email, i) {
  var username = email.slice(0, email.indexOf('@'));
  if(!usernames[username]) usernames[username] = true;
  return usernames;
}, {});

var usernames = Object.keys(usernameHash)

document.write(usernames.join(', '));