Webars Webars - 1 year ago 61
jQuery Question

How to use $.unique() function

Please, help me to understand, how to use


From the docs:

Sorts an array of DOM elements, in place, with the duplicates removed.

I'm trying this code:

<h1 class="foo">Headline</h1>
<h1 class="foo">Headline</h1>
<h1 class="foo">Headline</h1>

alert( $.unique($('.foo')).length );

It returns 3, but I supposed 1. What am I missing? And it would be great to see some practice example of using this function. Thanks.


I've also tried to sort a few numbers, but got a very curious result.
The following code returns different values in different browsers!

$.unique([ 1, 2, 2, 3, 3, 1 ])

  • Safari - 1, 2, 3, 1

  • Opera - 2, 1, 3

  • FF - 3, 2, 1, 3

  • Chrome - 3, 2, 1

  • IE - 2, 1, 3

Answer Source

$.unique is only meant for arrays of DOM elements. Not arrays of other things.

In your case, you have 3 <h3>s. They are not the same DOM element, so $.unique doesn't remove them.

<h1 class="foo">Headline</h1>
<h1 class="foo">Headline</h1>
<h1 class="foo">Headline</h1>

alert($.unique($('.foo')).length);  // 3

$.unique is for arrays that may contain the same element multiple times.

<h1 class="foo otherFoo">Headline</h1>
<h1 class="foo">Headline</h1>

var $foo = $('.foo').get();
var $otherFoo = $('.otherFoo').get();

var $e = $foo.concat($otherFoo);
alert($e.length); // 3
alert($.unique($e).length); // 2

On another note, if you want to make $.unique sort arrays of other things, and not just DOMElements, you can do something like this (Taken from here):

    var _old = $.unique;
    $.unique = function(arr){
        // do the default behavior only if we got an array of elements
        if (!!arr[0].nodeType){
            return _old.apply(this,arguments);
        else {
            // reduce the array to contain no dupes via grep/inArray
            return $.grep(arr,function(v,k){
                return $.inArray(v,arr) === k;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download