JQuery:删除重复的元素? [英] JQuery: Remove duplicate elements?

查看:86
本文介绍了JQuery:删除重复的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个链接列表,重复的值如下:

 < a href =#>书< / A> 
< a href =#> Magazine< / a>
< a href =#>书< / a>
< a href =#>书< / a>
< a href =#> DVD< / a>
< a href =#> DVD< / a>
< a href =#> DVD< / a>
< a href =#>书< / a>

我如何使用JQuery删除dup,并留下以下内容: p>

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

基本上,我正在寻找一种方法来删除所有重复的值,并显示每个链接的1个。 / p>

解决方案

  var seen = {}; 
$('a')。each(function(){
var txt = $(this).text();
if(seen [txt])
$这个).remove();
else
seen [txt] = true;
});

说明:



看到是将以前看到的任何文本映射到 true 的对象。它作为设置,其中包含所有以前看到的文本。 if(seen [txt])检查文本是否在集合中。如果是这样,我们之前看过这个文字,所以我们删除链接。否则,这是我们第一次看到的链接文本。我们将其添加到集合中,以便将删除具有相同文本的任何进一步链接。



表示集合的另一种方法是使用包含所有值的数组。然而,这将使它慢得多,因为看到数组中是否有数值,我们每次都需要扫描整个数组。相比之下,使用看到[txt] 的对象中的关键字非常快。


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.

解决方案

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.

这篇关于JQuery:删除重复的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆