Timothy Bassett
Timothy Bassett

Reputation: 129

jquery: check for duplicates in multiple lists

I have the following code:

<ul id="listOne">
    <li>John</li>
    <li>James</li>
    <li>Mary</li>
</ul>

<ul id="listTwo">
    <li>John</li>
    <li>Mark</li>
    <li>Mary</li>
</ul>

What I want to do is hide any objects in the 2nd list if they are already in the 1st list.

Can anyone suggest anything?

Upvotes: 4

Views: 1239

Answers (2)

Richard Dalton
Richard Dalton

Reputation: 35793

I would map the first list to an array then filter the second list values that have matching text and hide those like this:

var values = $('#listOne li').map(function() { 
    return $(this).text();
}).get();

$('#listTwo li').filter(function() {
    return $.inArray($(this).text(), values) !== -1;
}).hide();

http://jsfiddle.net/infernalbadger/unTMz/

Upvotes: 1

James Allardice
James Allardice

Reputation: 165971

There may be a slightly better way, but this is what came to mind first:

var firstList = [];
$("#listOne li").each(function() {
    firstList.push($(this).text());
});
$("#listTwo li").filter(function() {
    return firstList.indexOf($(this).text()) > -1;
}).remove();

Here's a working example. It builds an array of the text of the items in the first list, then filters the items of the second list to return only those which are also in the first list, and then removes the matched items from the DOM.

Upvotes: 5

Related Questions