JQuery Remove duplicate elements: It’s very easy to remove duplicate elements from a list using jQuery.

Demo:

Let’s say we have below list:

jquery remove duplicate elements

Here multiple duplicate values are there, Test 1, Test 3 and Test 2. Using jQuery we can easily remove them, refer the below code.

var seen = {};
$('p').each(function() {
    var txt = $(this).text();
    if (seen[txt])
         $(this).remove();
    else
	 seen[txt] = true;
});
  • seen is an object which maps any previously seen text to true.
  • Loop all p elements.
  • If any seen[txt] is exists then it will be removed using remove().

Full Code :

<!DOCTYPE html>
<html>
<head>
	<title>Remove duplicate Elements</title>
</head>
<body>
	<p>Test 1</p>
	<p>Test 2</p>
	<p>Test 1</p>
	<p>Test 3</p>
	<p>Test 4</p>
	<p>Test 3</p>
	<p>Test 1</p>
	<p>Test 5</p>
	<p>Test 2</p>
</body>
</html>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
	$(document).ready(function()
	{
		var seen = {};
		$('p').each(function() {
		    var txt = $(this).text();
		    if (seen[txt])
		        $(this).remove();
		    else
		        seen[txt] = true;
		});
	});
</script>

Include https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js for jQuery

Refer jQuery for more relatedsolutions.

Leave A Comment