In Python, if we have a list,
array = [1,2,3,4,5]
If we say array.count(1)
, it will return the count of 1 in array
.
Is there a method like this in javascript?
In Python, if we have a list,
array = [1,2,3,4,5]
If we say array.count(1)
, it will return the count of 1 in array
.
Is there a method like this in javascript?
I think there isn't. But you can make one by using prototype
.
let array = [1,2,3,4,5,1];
Array.prototype.count = function(value) {
let count = 0;
this.forEach(item => {
if (item === value) {
count++;
}
});
return count;
}
console.log(array.count(1));
console.log(array.count(2));