Strip duplicate values from a comma separated string using Javascript

This function will remove duplicate values from a comma separated string, returning only unique values in the original order.

I encountered a problem when developing a map application using the Google Maps API. When carrying out a reverse geocode call passing a lat/long string to retrieve a physical address, the API function would return the address but sometimes it would also contain duplicate values in the address if Google couldn’t get a specific house number or street name. For example: “Boston, Boston, MA, United States”.

To solve this problem the following Javascript function was created which accepts a string value, does some splitting and trimming of the string and returns only the unique values, with the commas still in place.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function stripDuplicateValues(inValue) 
        {
            var items = inValue.split(",");
            var arrlen = items.length -1;
            var i = 0;
            var outValue = "";
            var prevItem;
                while (i <= arrlen) 
                {
                    if (outValue.length > 0) 
                    {
                        if (prevItem != items[i].trim())
                        {
                            var str = items[i].trim();
                            outValue = outValue.replace(prevItem + ",", "");
                            outValue += ", " + str;
                        }
                    }
                    else 
                    {
                        outValue = items[i].trim();
                    }
                    prevItem = items[i].trim();
                    i++;
                }
            return outValue;
        }

Using the original example, the following would be returned: “Boston, MA, United States”.

2 thoughts on “Strip duplicate values from a comma separated string using Javascript”

Leave a Reply