Remove occurrences of duplicate words in a string

前端 未结 9 1993
野性不改
野性不改 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: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(', ');
    

提交回复
热议问题