How To Find The Number Of Times An Item Appears In An Array

  • Programming
  • Sat Oct 23 2021
  • Read Times: 83
  • Shares: 0
  • Likes: 0

If you are coming from a Python background, then you obviously know about the count method in the list class.

In JavaScript, there is nothing as the count method. For those of you who don’t know what the count method does is that, it counts the number of times an item appears in an array. For example, say we are having an array called numbers and we want to find the number of times the number two appeared in the array, this is how we would do it in Python.

numbers = [1,2,3,4,5,2,3,4,2,4,2]
print(numbers.count(2)) # => 4

Since the number two appeared four times in the array, the function would return the number 4.

Since this method does not exist in JavaScript, I decided to create my own count method.

Code

Array.prototype.count = function(item){
	return this.filter(x => x === item).length
	}

Explanation

In the code above, I extended the Array class and added a new method called count through the prototype. The method takes an argument called item. It then filters the array and return the length of the remaining items.
Simple.

Using The Code

In order to use the code, just create an array and call the count method like this.

let names = ["David","Walsh","David","Tania","Lucretius"];
names.count("David") //=> 2

Happy Coding Fellas 😄

Thanks to @frankwisniewski for finding a much better way to write the count method
0