tags:

views:

73

answers:

3

I've got a string with no spaces with ',' and duplicate entries. Why jQuery do not removing this?
var arr = $.unique(data.split(','));

A: 

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;
}
Anurag
+1  A: 

$.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.

Nick Craver
Is there any way to remove duplicates instead of writing own function??
smsteel
@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
+2  A: 

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.

Pekka