Skip to content
Advertisement

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

Advertisement

Answer

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(',')
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement