How to Count Occurrences of an Element in an Array in JavaScript.
JavaScript is a versatile language that offers many powerful methods for working with arrays. One common task developers often need to perform is counting the occurrences of a specific element within an array.
The most straightforward and commonly used approach is to use the filter()
method. This method allows you to filter out elements that meet a specific condition and then simply count how many items match that condition.
const array = [1,2,3,4,2,2,5,6,2,4,5];
const elementToCount= 2;
//Count occurrences of the element
const count = array.filter(item => item === elementToCount).length;
console.log(count); //Output: 4
filter() creates a new array containing only the elements that satisfy the condition item === elementToCount
..length
gives the number of elements in this new array, which is the count of the element you want.