Take the following string as an example:
var string = \"spanner, span, spaniel, span\";
From this string I would like to find the duplicate
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(', ');