Remove occurrences of duplicate words in a string

前端 未结 9 1942
野性不改
野性不改 2020-11-27 07:37

Take the following string as an example:

var string = \"spanner, span, spaniel, span\";

From this string I would like to find the duplicate

相关标签:
9条回答
  • 2020-11-27 08:16
    // Take the following string
    var string = "spanner, span, spaniel, span";
    var arr = string.split(", ");
    var unique = [];
    $.each(arr, function (index,word) {
        if ($.inArray(word, unique) === -1) 
            unique.push(word);
    
    });
    
    alert(unique);
    

    Live DEMO

    0 讨论(0)
  • 2020-11-27 08:17

    Both the other answers would work fine, although the filter array method used by PSL was added in ECMAScript 5 and won't be available in old browsers.

    If you are handling long strings then using $.inArray/Array.indexOf isn't the most efficient way of checking if you've seen an item before (it would involve scanning the whole array each time). Instead you could store each word as a key in an object and take advantage of hash-based look-ups which will be much faster than reading through a large array.

    var tmp={};
    var arrOut=[];
    $.each(string.split(', '), function(_,word){
        if (!(word in tmp)){
            tmp[word]=1;
            arrOut.push(word);
        }
    });
    arrOut.join(', ');
    
    0 讨论(0)
  • 2020-11-27 08:18

    If non of the above works for you here is another way:

    var str = "spanner, span, spaniel, span";
    str = str.replace(/[ ]/g,"").split(",");
    var result = [];
    for(var i =0; i < str.length ; i++){
        if(result.indexOf(str[i]) == -1) result.push(str[i]);
    }
    result=result.join(", ");
    

    Or if you want it to be in a better shape try this:

    Array.prototype.removeDuplicate = function(){
       var result = [];
       for(var i =0; i < this.length ; i++){
           if(result.indexOf(this[i]) == -1) result.push(this[i]);
       }
       return result;
    }
    var str = "spanner, span, spaniel, span";
    str = str.replace(/[ ]/g,"").split(",").removeDuplicate().join(", ");
    
    0 讨论(0)
提交回复
热议问题