1

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); 

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@systempuntoout: and use $('li.category1,li.category2').get();
0

You could just do this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.