• John
  • James
  • Mary<...">

    Jquery: checking 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 second list if they are already in the first list.

    Can anyone suggest something?

    +4
    source share
    2 answers

    It might be a little better, but first it came to mind:

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

    Here is a working example . It builds an array of text of elements in the first list, then filters the elements of the second list to return only those that are also in the first list, and then removes the matching elements from the DOM.

    +5
    source

    I would map the first list to an array, then filter the values โ€‹โ€‹of the second list having the corresponding text, and hide those that look 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/

    +1
    source

    Source: https://habr.com/ru/post/1382678/


    All Articles