How to usefilter() method in Javascript

The JavaScript Array filter() Method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method. 

Syntax:

array.filter(callback(element, index, arr), thisValue)

Example: In this example, the filter() method is used to count the frequency of the elements of the array. We are printing the frequency of “1” in the array in the console.

Javascript




let arr = [1, 2, 3, 2, 3, 4, 5,
           5, 6, 1, 1, 4, 5, 7, 8, 8];
 
function count(arr, element) {
    return arr.filter(
        (ele) => ele == element).length;
};
 
console.log(count(arr, 1))


Output:

3

Count Frequency of an Array Item in JavaScript

In this article, we will be counting the frequency of an array item in Javascript.

When working with arrays there are situations when we need to count the frequency of an array item. Javascript provides us with some methods to count the occurrences of an item in an array, some of them are explained below:

Similar Reads

Approach 1: Using for loop

The Javascript for loop is used to iterate over the elements of an array and is used to count the number of occurrences of elements in the array....

Approach 2: Using filter() method

...

Approach 3: Using reduce() method:

The JavaScript Array filter() Method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method....

Approach 4: Using for-of loop:

...