I've got a string with no spaces with ',' and duplicate entries. Why jQuery do not removing this?
var arr = $.unique(data.split(','));
 
    
    - 1,403
- 2
- 15
- 29
- 
                    Please provide a full code sample and use professional language. – a'r Aug 09 '10 at 11:11
- 
                    Lol? I've posted it. I've got string like var data = "omg,lol,omg". – UnstableFractal Aug 09 '10 at 11:12
3 Answers
I think you're not using the right function for this.
From the jQuery documentation on $.unique:
Note that this only works on arrays of DOM elements, not strings or numbers.
This SO question contains some approaches for a generic array_unique solution.
$.unique() isn't assured to work on arrays of strings, it has a specific purpose, check the API:
This function only works on plain JavaScript arrays of DOM elements, and is chiefly used internally by jQuery.
 
    
    - 623,446
- 136
- 1,297
- 1,155
- 
                    Is there any way to remove duplicates instead of writing own function?? – UnstableFractal Aug 09 '10 at 11:15
- 
                    @smsteel - jQuery doesn't have a function built-in for this no...that isn't it's purpose really, but a function isn't hard to write, see the question Pekka linked in his answer. – Nick Craver Aug 09 '10 at 11:20
Console says:
> var data = "omg,lol,omg";
> $.unique(data.split(","))
["lol", "omg"]
However it is unreliable because it is meant to be used with DOM nodes. The sorting function that it uses is used to compare DOM nodes and is browser-specific. If you want to de-duplicate an array of strings, then the algorithm used by jQuery.unique can be reused. Sort the array, and remove all consecutive matching elements.
function removeDuplicates(array) {
    array.sort();
    for(var i = 1; i < array.length; i++) {
        if(array[i] == array[i-1]) {
            array.splice(i--, 1);
        }
    }
    return array;
}
 
    
    - 140,337
- 36
- 221
- 257
 
    