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