简体   繁体   English

删除数组中的相同项目

[英]Removing identical items in an array

Beginner programmer here. 初学者程序员在这里。 I'm struggling with an assignment that's taking input text, splitting the words into single array items and then listing the total number of each words in an output. 我在分配输入文本,将单词分成单个数组项然后列出输出中每个单词的总数的分配工作中苦苦挣扎。 The splitting of the input works fine, but I need to check the array for duplicate items and remove that item (need to keep it unique) while also increasing the count on that particular word. 输入的拆分工作正常,但我需要检查数组中是否存在重复项,并删除该项(需要使其保持唯一),同时还要增加该特定单词的计数。

The idea was to make an array consisting of the words alone, and another that keeps track of the count. 想法是制作一个仅由单词组成的数组,另一个数组则保持计数。 Glad to receive tips to use a simpler approach as well. 很高兴收到使用更简单方法的提示。

And yes, I know there is several solutions to this problem on SO, but I dont quite understand how to fix this particular code using functions. 是的,我知道在SO上有几个解决此问题的方法,但是我不太了解如何使用函数修复此特定代码。

function gen()
{   
    var arr = [];
    var counter = [];
    var str = document.getElementById("inpTxt").value;
    str.toString();
    str = str.split(" ");

    for(var i = 0; i < str.length; i++) 
    {
        arr.push(str[i]);                                   
        counter[i]++; //ignore that this array hasnt been properly declared yet, Im trying to make this equal length of arr with default value 0
        //tried nested loop here for making comparison, didnt work

        document.getElementById("print").innerHTML += "Total number of the word \"" + arr[i] + "\": " + counter[i] + " <br />";
    }
}

If you're using ECMAScript2015(ES6), you can build a Set - which guarantees unicity - from your array : 如果您使用ECMAScript2015(ES6),你可以建立一个Set -这保证唯一性-从你的阵列:

var inputArray = [1, 1, 2, 3, 2, 4, 5, 5, 4, 1];
console.log(new Set(inputArray)) // displays Set { 1, 2, 3, 4, 5 }

Otherwise, you can loop over the array and check if a particular element follows another occurrence of itself : 否则,您可以遍历数组并检查特定元素是否跟随其自身的另一次出现:

var inputArray = [1, 1, 2, 3, 2, 4, 5, 5, 4, 1];
// with ES6 :
var result = inputArray.filter((element, index) => ! inputArray.slice(0, index).includes(element));
// without ES6 :
result=[];
for (var i=0; i<inputArray.length; i++) {
    var currentElement = inputArray[i];
    var previouslyFound = false;
    for (var j=0; j<i && !previouslyFound; j++) {
        previouslyFound = inputArray[i] == inputArray[j];
    }
    if (!previouslyFound) result.push(currentElement);
}

However, since we are looping over the array, it would be as fast to count the occurrences without unicizing the array first : 但是,由于我们要遍历数组,因此在不先使数组不统一的情况下对出现的次数进行计数就一样快:

var inputArray = [1, 1, 2, 3, 2, 4, 5, 5, 4, 1];
// with ES6 :
var result = inputArray.reduce(function(map, element) {
    map[element] = map.hasOwnProperty(element) ? map[element] + 1 : 1;
    return map;
}, {});
// without ES6 :
var result = {};
for (var i=0; i<inputArray.length; i++) {
    var currentElement = inputArray[i];
    if (result.hasOwnProperty(currentElement)) {
        result[currentElement] = result[currentElement] + 1;
    } else {
        result[currentElement] = 1;
    }
}

Try the indexOf method of arrays to figure out whether you already have the string in array. 尝试使用数组的indexOf方法来确定数组中是否已经有字符串。

 function gen()
    {   
        var arr = [];
        var counter = [];
        var str = document.getElementById("inpTxt").value;
        str.toString();
        str = str.split(" ");

        for(var i=0; i < str.length; i++)   
        {
          if(arr.indexOf(str)==-1){                    
          arr.push(str[i]);                                   
            counter[i]++; //ignore that this array hasnt been properly declared yet, Im trying to make this equal length of arr with default value 0
          }
            //tried nested loop here for making comparison, didnt work

            document.getElementById("print").innerHTML += "Total number of the word \"" + arr[i] + "\": " + counter[i] + " <br />";
        }
    }

PS: please know that there are less expensive methods available out there but i am just trying to help with whatever i can. PS:请知道那里有较便宜的方法,但是我只是想尽一切可能帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM