Remove duplicate characters from string

前端 未结 28 986
猫巷女王i
猫巷女王i 2020-12-01 13:09

I have to make a function in JavaScript that removes all duplicated letters in a string. So far I\'ve been able to do this: If I have the word \"anaconda\" it shows me as a

28条回答
  •  广开言路
    2020-12-01 13:49

    I have FF/Chrome, on which this works:

    var h={}; 
    "anaconda".split("").
      map(function(c){h[c] |= 0; h[c]++; return c}).
      filter(function(c){return h[c] == 1}).
      join("")
    

    Which you can reuse if you write a function like:

    function nonRepeaters(s) {
      var h={}; 
      return s.split("").
        map(function(c){h[c] |= 0; h[c]++; return c}).
        filter(function(c){return h[c] == 1}).
        join("");
     }
    

    For older browsers that lack map, filter etc, I'm guessing that it could be emulated by jQuery or prototype...

提交回复
热议问题