You need to sort the word alphabetically with the exception of duplicate letters.

let's say there is a трафарет word -> there will be an аертф .

that the word can be accessed as an array I am aware of, but .sort() does not apply.

  • str.split("") -> array of letters - Visman
  • string.split('').sort().join('') - Sergiks
  • not quite caught up .. break the string by splitting the void separator ?? - pirogi
  • 2
    @pirogi, and the test is weak? - Visman
  • What about upper and lower case letters? From "Alphabet" are you ready to get "Aaviltf"? - Sergiks

2 answers 2

You can, for example, like this:

 var original = 'трафарет', sorted = '', res = ''; sorted = original.split('').sort(function (a, b) { return a.localeCompare(b); }).join(''); for (var i = 0, l = sorted.length; i < l; i++) { if (res.indexOf(sorted[i]) > -1) { continue; } res += sorted[i]; } console.log(res); 
  • My condition is correct. I check if the last letter of the result is current in the sorted string. Although indexOf(sorted[i]) really shorter :-) Fixed. - Dmitriy Simushev
  • there is a small redundancy: each letter is searched throughout the alphabet at that time. Do not use the fact that the line is already sorted. - Sergiks
  • @Sergiks, I agree. You can use res.length > 0 && res[res.length - 1] === sorted[i] in the condition; it is faster, but worse to read. - Dmitriy Simushev
  • @Sergiks: and so it was, I did not understand it at first and confused the author of the answer indexOf :) - vas
  • @shatal, if I choose between the readability of the code and the speed of its execution (within reasonable limits, of course), I choose readability. That is why I left indexOf :-) - Dmitriy Simushev

Sort, then exclude duplicates:

 function letters( word) { var alphabet = word.split('').sort().join('') ,i ,prev ,out='' ; for(i=0; i<alphabet.length; i++) { if( prev==alphabet.charAt(i)) continue; prev = alphabet.charAt(i); out = out + prev; } return out; } document.body.innerHTML = letters('трафарет'); // аертф 

Feeddle