Skip to content

JavaScript count Array elements | Example code

  • by

Use for loop to get count array elements in JavaScript. Let’s see HTML example code:-

Count certain elements in Array

<!DOCTYPE HTML> 
<html> 
<body> 

	<script>
		var arr = [1, 2, 3, 5, 2, 8, 9, 2];

		var count = 0;
		for(var i = 0; i < arr.length; ++i){
			if(arr[i] == 2)
				count++;
		}
		console.log(count);
	</script> 
</body> 
</html>	

Output:

JavaScript Count certain elements in Array

Use JavaScript array length property returns get count of total elements in the Array.

Get number of elements in an array.

<!DOCTYPE HTML> 
<html> 
<body> 

	<script>
		var arr = [1, 2, 3, 5, 2, 8, 9, 2];

		var count = arr.length;
		
		console.log(count);
	</script> 
</body> 
</html>

Output: 8

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

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading