0

I have string values that contain a list of items separated with a comma, e.g. the value could be val1,val2,val3,val1,val4,val3,val2,val5.

Is there an easy way I can remove all duplicates from such a string so that each value only appears once within the string ?

E.g. in the above example I would like to get val1,val2,val3,val4,val5 instead.

Many thanks in advance, Tim.

Barmar
  • 741,623
  • 53
  • 500
  • 612
user2571510
  • 11,167
  • 39
  • 92
  • 138
  • 1
    You would need a nested for loop to check each element after you split this string using string.split(","). You're probably better of checking for duplicates when you add an item to this string. – annemartijn Mar 02 '14 at 12:42

1 Answers1

9

Make an array by split string and use unique() try like this:

 data = "val1,val2,val3,val4,val5";
 arr =  $.unique(data.split(','));
 data = arr.join(","); //get unique string back with 

live demo

Awlad Liton
  • 9,366
  • 2
  • 27
  • 53