If you have a Python background, you are probably familiar with the count
method in the list class.
The count
method does not exist in JavaScript. For those unfamiliar with the count
method, it counts the number of times an item appears in an array. For example, suppose we have a numbers
array, and we want to find the number of times the number '2' appears in the array. In Python, we would do it like this.
numbers = [1,2,3,4,5,2,3,4,2,4,2]
print(numbers.count(2)) # => 4
The code would return 4 because the number '2' appears four times in the array.
Since this technique did not exist in JavaScript, I decided to write my own.
Array.prototype.count = function (item) {
return this.filter((x) => x === item).length;
};
Extending JavaScript inbuilt classes can cause unexpected behaviour and conflicts with other libraries, so it's better to create custom classes instead.
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 returns the number of times item
was found in the array.
To utilise the code, simply construct an array and call the count method as shown below.
let names = ['David', 'Walsh', 'David', 'Tania', 'Lucretius'];
names.count('David'); //=> 2
Top comments (8)
thanks man
Hey @frankwisniewski,
You method is much simpler. I guess I will have to update my code.
Anyways, thanks for the help๐ฅณ๐ฅณ
clean and short ๐
another way to do it:
Wow๐ค
Extending prototypes in this way is dangerous and should be done with great care. Don't forget, you are extending a core part of JS that is relied on by pretty much everything else. There's no guarantee that your code will not conflict with other code that attempts to do something similar, or will be compatible with future updates of JS itself.
That said, there are ways to do this kind of thing safely. I recently wrote a library that can be used to help you safely extend native prototypes in this manner. I call it Metho. Take a look if you're interested ๐
Hey @jonrandy metho seems really cool. I write an article about it soon