-1

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?

Henry Woody
  • 14,024
  • 7
  • 39
  • 56
asgarov
  • 41
  • 6
  • 2
    Does this answer your question? [How to count the number of certain element in an array?](https://stackoverflow.com/questions/6120931/how-to-count-the-number-of-certain-element-in-an-array) –  Apr 19 '20 at 18:30
  • Does this answer your question? [Counting the occurrences / frequency of array elements](https://stackoverflow.com/questions/5667888/counting-the-occurrences-frequency-of-array-elements) – robere2 Apr 19 '20 at 18:30
  • 1
    `array.filter((x) => x === ).length` – Ben Aston Apr 20 '20 at 07:30

1 Answers1

2

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));
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30