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

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.