0

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?

3

1 Answer 1

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));

Not the answer you're looking for? Browse other questions tagged or ask your own question.