Count Frequency of an Array Item in JavaScript
Last Updated :
14 Nov, 2024
Improve
Here are the different approaches to count the frequency of an Array Item in JavaScript
Using a Loop and Counter
This is the most basic and efficient approach when you want to find the frequency of a single item. You simply loop through the array and count how many times the item appears.
const frequency = (arr, item) => {
let count = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === item) {
count++;
}
}
return count;
};
const a = [1, 2, 3, 2, 1, 2, 3, 1];
console.log(frequency(a, 2));
Output
3
Using filter() Method
You can filter the array to only include occurrences of the target element and then return the length of the filtered array.
const frequency = (arr, item) => {
return arr.filter(x => x === item).length;
};
const a = [1, 2, 3, 2, 1, 2, 3, 1];
console.log(frequency(a, 2));
Output
3
Using reduce() Method
The reduce() method can also be used to accumulate the frequency of a single item by checking each element in the array.
const frequency = (arr, item) => {
return arr.reduce((count, x) => x === item ? count + 1 : count, 0);
};
const a = [1, 2, 3, 2, 1, 2, 3, 1];
console.log(frequency(a, 2));
Output
3
Using an Object (for Larger Arrays)
If you're working with larger arrays and you want to count occurrences efficiently, an object can be used to store counts of all items. But you can optimize it for a single item by simply counting the target item.
const frequency = (a, item) => {
const o = {};
a.forEach(x => {
if (x === item) {
o[item] = (o[item] || 0) + 1;
}
});
return o[item] || 0;
};
const a = [1, 2, 3, 2, 1, 2, 3, 1];
console.log(frequency(a, 2));
Output
3