Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 4. jQuery Utilities > Filtering Out Duplicate Array Entries with jQuery...

4.7. Filtering Out Duplicate Array Entries with jQuery.unique

4.7.1. Problem

You have two jQuery DOM collections that need to have duplicate elements removed:

(function($) {
    $(document).ready(function() {
        var animals = $('li.animals').get();
        var horses = $('li.horses').get();
        $('#animals')
            .append( $(animals).clone() )
            .append( $(horses).clone() );
    });
})(jQuery);

4.7.2. Solution

(function($) {
    $(document).ready(function() {
        var animals = $('li.animals').get();
        var horses = $('li.horses').get();
        var tmp = $.merge( animals, horses );
        tmp = $.unique( tmp );
        $('#animals').append( $(tmp).clone() );
    });
})(jQuery);

4.7.3. Discussion

jQuery’s $.unique() function will remove duplicate DOM elements from an array or collection. In the previous recipe, we combine the animals and horses arrays using $.merge(). jQuery makes use of $.unique() throughout most of its core and internal functions such as .find() and .add(). Thus, the most common use case for this method is when operating on an array of elements not constructed with jQuery.