JQuery: Remove duplicate elements?

2019-01-01 12:59发布

Say I have a list of links with duplicate values as below:

<a href="#">Book</a>
<a href="#">Magazine</a>
<a href="#">Book</a>
<a href="#">Book</a>
<a href="#">DVD</a>
<a href="#">DVD</a>
<a href="#">DVD</a>
<a href="#">Book</a>

How would I, using JQuery, remove the dups and be left with the following for example:

<a href="#">Book</a>
<a href="#">Magazine</a>
<a href="#">DVD</a>

Basically I am looking for a way to remove any duplicate values found and show 1 of each link.

8条回答
查无此人
2楼-- · 2019-01-01 13:36
var seen = {};
$('a').each(function() {
    var txt = $(this).text();
    if (seen[txt])
        $(this).remove();
    else
        seen[txt] = true;
});

Explanation:

seen is an object which maps any previously seen text to true. It functions as a set containing all previously seen texts. The line if (seen[txt]) checks to see if the text is in the set. If so, we've seen this text before, so we remove the link. Otherwise, this is a link text we see for the first time. We add it to the set so that any further links with the same text will be removed.

An alternative way to represent a set is to use an array containing all values. However, this would make it much slower since to see if a value is in the array we'd need to scan the entire array each time. Looking up a key in an object using seen[txt] is very fast in comparison.

查看更多
长期被迫恋爱
3楼-- · 2019-01-01 13:37

Use jQuery method $.unique()

Detail see on http://api.jquery.com/jQuery.unique/

查看更多
一个人的天荒地老
4楼-- · 2019-01-01 13:42

A quick and easy way would be

$("a").​​​​​​​​each(function(){
    if($(this).parent().length)
        $("a:contains('" + $(this).html() + "')").not(this).remove();
});​
查看更多
长期被迫恋爱
5楼-- · 2019-01-01 13:42
$('.photo').each(function (index) { 
    if (index > 0) { 
        $(this).remove(); 
    } 
});
查看更多
与君花间醉酒
6楼-- · 2019-01-01 13:43
// use an object as map
var map = {};
$("a").each(function(){
    var value = $(this).text();
    if (map[value] == null){
        map[value] = true;
    } else {
        $(this).remove();
    }
});
查看更多
临风纵饮
7楼-- · 2019-01-01 13:50

@interjay @Georg Fritzsche

Your fix didn't work in my case so I build a different version:

var seen='';
   $('a').each(function(){
        var see=$(this).text();
        if(seen.match(see)){
            $(this).remove();}
        else{
            seen=seen+$(this).text();
        }
    });

Hopes this provides someone else with a valid alternative short fix just in case.

查看更多
登录 后发表回答