Reputation: 127
Is it possible to remove duplicated values in a string?
e.g: aaa, bbb, ccc, ddd, bbb, ccc, eee, fff, ggg
the expected output be like: aaa, bbb, ccc, ddd, eee, fff, ggg
I have no idea how should I achieve on this.
Upvotes: 0
Views: 65
Reputation: 92854
EcmaScript5 solution using String.prototype.match()
and Array.prototype.filter()
functions:
var str = 'aaa, bbb, ccc, ddd, bbb, ccc, eee, fff, ggg',
unique_items = str.match(/\b\w+\b/g).filter(function (el, idx, a) {
return idx === a.lastIndexOf(el);
});
// unique_items.sort(); // to get a sorted list of words(alphabetically)
console.log(unique_items);
// back to string
console.log(unique_items.join(', '));
It will also cover such sophisticated input strings as 'aaa, bbb,, ccc, ddd, bbb, ccc? eee,, fff, ggg,,'
Upvotes: 1
Reputation: 618
Using Reduce Function with out disturb the existing order
var names = ["No","Speaking","Guy","No","Test","Solutions","No"];
var uniq = names.reduce(function(a,b){
if (a.indexOf(b) < 0 ) a.push(b);
return a;
},[]);
console.log(uniq, names) // [ 'No', 'Speaking', 'Guy', 'Test', 'Solutions' ]
// one liner
return names.reduce(function(a,b){if(a.indexOf(b)<0)a.push(b);return a;},[]);
Upvotes: 1
Reputation: 4039
Split the string at the commas and then put the result array in a Set. The set object is like an array, but it only stores 1 of each value.
var set = new Set(yourString.split(","));
var distinctValues = Array.from(set).join();
Upvotes: 0