-2

I need to remove duplicate characters from string, for example: "abcdab" => "abcd" "aaabbc" => "abc" How to do it on JS (maybee with using $.unique or something else) ?

Letfar
  • 3,253
  • 6
  • 25
  • 35

2 Answers2

5

function unique(str) {
  var result = '';
  for(var i = 0; i < str.length; i++) {
    if(result.indexOf(str[i]) < 0) {
      result += str[i];
    }
  }
  return result;
}

console.log(
  unique('abcdab'),
  unique('aaabbc')
);
Chris Happy
  • 7,088
  • 2
  • 22
  • 49
Amit
  • 45,440
  • 9
  • 78
  • 110
0

I would turn the string into an array with split("") and pass it to underscore's unique function then join it back up.

$.unique("abcdab".split("")).join("");

edit: working jsbin http://jsbin.com/wakonepala/1/edit?js,console

John Moses
  • 1,283
  • 1
  • 12
  • 18