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
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
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.
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;
});
}
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);
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);
});
If they are only integers, you could have something like that:
var array = "1,2,2,4,2,4,3,2,3,1,5,5,5,1,1,2".split(",");
array.sort(function(a, b) { return a - b });
var uniqueArray = [array[0]];
for (var i = 1; i < array.length; i++) {
if (array[i - 1] !== array[i])
uniqueArray.push(array[i]);
}
console.log(uniqueArray);
you can create a function in your javascript as follows:
Array.prototype.removeDuplicates = function () {
return this.filter(function (item, index, self) {
return self.indexOf(item) == index;
});
};
then add .removeDuplicates()
to the field you want the duplicates to be removed from after you split using the delimiter, such as:
var item = $("#inInputTextbox").val().split(",").removeDuplicates();
in your case, if i understand correctly, it could simply be:
var item = [a,b,c,d,d,d,c,b,a].split(",").removeDuplicates();
hope this helps.
var numbersString = "1,2,3,4,5,6";
var numbersArray = numbers.split(',');
Now just insert with check in another array the content of numbersArray