Count duplicate elements in array JavaScript | Example code

You have to do some coding in loop to get the count of duplicate elements in array JavaScript. We will do code using the forEach and for loop.

JavaScript count same elements in array Example

HTML example code:

Lengthy code:

In this code elements will be fetch from array and will counted in for loop.

<!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>	

Short code:

In this way you have to write elements name in the code. And for counting the elements using for-each loop.

<!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: Result will be same for both because the given array is same.

Count duplicate elements in array JavaScript

Do comment if you have any doubts and suggestions on this JS Array.

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.