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) ?
Asked
Active
Viewed 7,858 times
2 Answers
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
-
FWIW, I like my answer better than any of the "marked as duplicate" answer as it is shorter. – John Moses Sep 21 '15 at 22:08
-
That's jQuery, and doesn't work. – Amit Sep 21 '15 at 22:13
-
Thank, this is also a good solution. – Letfar Sep 21 '15 at 22:40
-
Hey @Amit, I added a jsbin to show it working. – John Moses Sep 22 '15 at 04:57
-
Again, it's ***not underscore***, and it [***doesn't work***](https://api.jquery.com/jQuery.unique/) (only works for DOM objects, sorts original array in place - so modifies input and returns a sorted result) – Amit Sep 22 '15 at 05:44