Skip to content

Count duplicates in array JavaScript | Example code

  • by

How to Count duplicates in array JavaScript?

There are many ways to count duplicates in Array using JavaScript. Like using sorting and for loop or hard-coded elements for each method.

Let’s see HTML example code for it:-

The long way

<!DOCTYPE HTML> 
<html> 
<body> 
 
	<script>
		var elements = ["Apple", "Apple", "Orange", "Apple", "Banana"];
 
		elements.sort();
 
		var current = null;
		var count = 0;
 
		for(var i = 0; i < elements.length; i++)
		{
			if(elements[i] != current)
			{
				if(count > 0)
				{
					document.write(current + " " + count + "<br/>");
				}
				current = elements[i];
				count = 1;
			}
			else
			{
				count++;
			}
		}
 
		if(count > 0)
		{
			document.write(current + " " + count);
		}
	</script> 
</body> 
</html>		

The short way

<!DOCTYPE HTML> 
<html> 
<body> 
 
	<script>
		var elements = ["Apple", "Apple", "Orange", "Apple", "Banana"];
 
		var counts = {};
 
		elements.forEach(function(x) {
			counts[x] = (counts[x] || 0) + 1;
		});
 
		document.write("Apple: " + counts.Apple + "<br/>");
		document.write("Banana: " + counts.Banana + "<br/>");
		document.write("Orange: " + counts.Orange + "<br/>");
	</script> 
</body> 
</html>		

Output: The result will be the same.

Count duplicates in array JavaScript

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this example.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *