-6

How i Remove duplicates from my string

var string="1,2,3,2,4,5,4,5,6,7,6";

But i want like this

var string="1,2,3,4,5,6,7";

3 Answers3

2

Yes you can do it easily, Here is the working example

data = "1,2,3,2,4,5,4,5,6,7,6";
arr =  $.unique(data.split(','));
data = arr.join(",");

console.log(data);
Praveen Rana
  • 440
  • 7
  • 21
0

Use the following to push unique values into a new array.

var names = [1,2,2,3,4,5,6];
var newNames = [];
$.each(names, function(index, value) {
    if($.inArray(value, newNames) === -1) 
        newNames.push(value);
});
roberrrt-s
  • 7,914
  • 2
  • 46
  • 57
Vikash Kumar
  • 1,712
  • 1
  • 11
  • 17
0

Create the following prototype and use it to remove duplicates from any array.

Array.prototype.unique = function () {
    var arrVal = this;
    var uniqueArr = [];
    for (var i = arrVal.length; i--; ) {
        var val = arrVal[i];
        if ($.inArray(val, uniqueArr) === -1) {
            uniqueArr.unshift(val);
        }
    }
    return uniqueArr;
}

Ex:

var str = "1,6,7,7,8,9";
var array1 = str.split(',');
var array1 = array1.unique();
console.log(array1);    // [1,6,7,8,9]
str = array1.join();
pd91
  • 41
  • 5