'sort unique values on the same line

If I have a list of items like this in any text-area, I can use a bookmarklet to sort the unique values.

a
b
d
c
c

I click on the bookmarklet and the list is corrected to:

a
b
c
d

code:

javascript: (
  function() {
    Array.from(document.querySelectorAll('textarea')).map(function(b) {
      var a = document.createElement('div');
      var d = document.createElement('button');
      d.textContent = '↑';
      d.addEventListener('click', function(f) {
        f.preventDefault();
        b.value = Array.from(new Set(b.value.split('\n'))).sort().join('\n')
      });
      var c = document.createElement('button');
      c.textContent = '↓';
      c.addEventListener('click', function(f) {
        f.preventDefault();
        b.value = Array.from(new Set(b.value.split('\n'))).sort().reverse().join('\n')
      });
      a.appendChild(d);
      a.appendChild(c);
      b.parentNode.insertBefore(a, b)
    })
  }
)();

But this does not work if all the items are on the same line like this...

a , b,d , c,c

Is it possible to modify the code to return the items like this...

a, b, c, d

I can do that in python. But I will like to know if it is possible using JavaScript bookmarklet.

myl = [i.strip() for i in text.split(',')]
myl.sort()
', '.join(set(myl))


Solution 1:[1]

This would work better because since your input has blank spaces in it ,we have to use regex to split the string.

b = Array.from(
new Set(b.split(/[ ,]+/))).sort().reverse().join(',')

Solution 2:[2]

You could try lodash for this purpose, As mentioned in other answers that you need to first change the words format from : a b d c c to : a,b,d,c,c

if changed

let x= // your values e.g a,b,d,c,c
//
let valuesArray=_.split(x,',')
uniqueFromArray=_.uniq(valuesArray)

if unchanged

let x= // your current input values 
//
let valuesArray=_.split(x,'\n')
uniqueFromArray=_.uniq(valuesArray)

Solution 3:[3]

On this line:

b.value = Array.from(
  new Set(b.value.split('\n'))).sort().reverse().join('\n')

You just need to change '\n' to ,, like:

b.value = Array.from(
  new Set(b.value.split(','))).sort().reverse().join(',');

b.value.forEach(item => item.trim()); //to remove trailing whitespaces

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arun
Solution 2 Ali Tasawar
Solution 3