Thursday, May 9, 2013

get distinct values from string


An easy way to remove duplicate from string and get distinct values


 var input = '1,2,3,1,4,6,7,2,3';
                var splitted = input.split(',');
                var collector = {};
                for (i = 0; i < splitted.length; i++) {
                    key = splitted[i].replace(/^\s*/, "").replace(/\s*$/, "");
                    collector[key] = true;
                }
                var out = [];
                for (var key in collector) {
                    out.push(key);
                }
                var output = out.join(',');

OutPut will be 1,2,3,4,6,7

No comments:

Post a Comment