Remove Duplicates From Comma Delimited String
14,426
Solution 1
For one method, which doesn't demand writing the functionality from scratch or using some other js library check out duck-punching-with-jquery. (look for 'Example 2: $.unique() enhancement')
If you're willing to try some other library, the excellent underscorejs includes a 'uniq' method which accomplishes just what you need.
Solution 2
function spit(){
var answer = ("1,2,2,4,2,4,3,2,3,1,5,5,5,1,1,2").split(',').filter(function(item, pos,self) {
return self.indexOf(item) == pos;
});
}
Solution 3
Here's a simple example.
var str1 = "a,b,c,a,d,e,b";
var characters = str1.split(",");
var distinctCharacters = [];
jQuery.each(characters, function(index, c) {
if (jQuery.inArray(c, distinctCharacters) > -1) {
// do nothing
alert("already exists " + c);
} else {
distinctCharacters.push(c);
}
});
alert(distinctCharacters);
Solution 4
From this post Remove Duplicates from JavaScript Array
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
Solution 5
good answers, there is also _.uniq()
from the library underscore.js
Author by
Tommy Arnold
Updated on June 05, 2022Comments
-
Tommy Arnold almost 2 years
How do I remove duplicates from a comma delimited string of integers using jquery/javascript?
My string is: 1,2,2,4,2,4,3,2,3,1,5,5,5,1,1,2