0

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.

3
  • @SandeepNayak string Commented Jan 6, 2017 at 7:47
  • Can you show what you have tried so far? Commented Jan 6, 2017 at 7:49
  • @PeterSmith to be fair i haven't tried much yet, because i'm kind of new to JS and like i said above, i have no idea how to go on it Commented Jan 6, 2017 at 7:50

3 Answers 3

1

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,,'

Sign up to request clarification or add additional context in comments.

2 Comments

is it just because it's the console.log or will the [] and "" appear in the output?
@Damon, pay attention, the answer gives the expected output, no empty strings
1

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;},[]);

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.