-1

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

UnstableFractal
  • 1,403
  • 2
  • 15
  • 29

3 Answers3

2

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.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
1

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

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
  • 140,337
  • 36
  • 221
  • 257