Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Remove duplicate elements?

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.

like image 896
Keith Donegan Avatar asked May 12 '10 21:05

Keith Donegan


People also ask

How do you remove duplicates from an array in place?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays.sort(arr) method.

How to find duplicate values in array in jQuery?

You can check if an array has duplicates using $. unique function on jQuery.

How do I remove duplicate values from a drop down list in HTML?

You also can remove the duplicates from the table list firstly, then create the drop down list. Select the column range you want to use in the table, the press Ctrl + C to copy it, and place it to another position by pressing Ctrl + V. Then keep selecting the list, click Data > Remove Duplicates.

How to remove duplicate values in array jQuery?

Answer: Use the indexOf() Method You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.


1 Answers

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.

like image 91
interjay Avatar answered Sep 20 '22 18:09

interjay