tags:

views:

47

answers:

2

How do i filter duplicates of two arrays before appending entries to a DOM node (#list)?

(function($) { 
    $(document).ready(function() { 
        var item_category1 = $('li.category1').get(); 
        var item_category2 = $('li.category2').get(); 
        $('#list') 
            .append( $(item_category1).clone() ) 
            .append( $(item_category2).clone() ); 
    }); 
})(jQuery); 
+3  A: 

jQuery has a utility called $.unique() that should work for you.

http://api.jquery.com/jQuery.unique/


EDIT:

As stated by others, if you have no need to interact with them separately, you can just get the whole of them in one call.

If you do need to perform some separate work on the two sets first, you can also add one set to the other when you're done.

var item_category1 = $('li.category1'); 
var item_category2 = $('li.category2');
    // Do what you need
var categories = item_category1.add(item_category2);
$('#list').append( categories.clone() ); ​

The resulting collection will be free of duplicates.

http://jsfiddle.net/2zXxK/1/

Gotta love jsFiddle.

patrick dw
@systempuntoout: and use `$('li.category1,li.category2').get();`
fudgey
A: 

You could just do this:

$('li.category1, li.category2').clone().appendTo('#list');
PetersenDidIt