JavaScript- Count Frequencies in an Array
These are the following ways to count the frequency:
1. Using Object (Efficient for Small to Moderate Arrays)
We use JavaScript Objects to store frequencies, we iterate over the array using the forEach() method. For each element, we check if the element already exists as a key in the res object. If it does, we increment its count; if not, we initialize it to 1.
const a = [4, 2, 3, 4, 3, 2, 4, 1, 3, 2];
let res = {};
a.forEach(e => {
res[e] = (res[e] || 0) + 1;
});
console.log(res);
2. Using Map (Easiest and Efficient for All Types of Arrays)
Here, we use a Map to store the frequency of each element. We iterate over the array using forEach() and use the get() method to check if the element is already in the Map.
const a1 = [4, 2, 3, 4, 3, 2, 4, 1, 3, 2];
let res = new Map();
a1.forEach(e => {
res.set(e, (res.get(e) || 0) + 1);
});
console.log(Object.fromEntries(res));
Output
{ '1': 1, '2': 3, '3': 3, '4': 3 }
3. Using reduce() with Map (Similar to 2nd)
This approach uses the reduce() method, which is typically used to accumulate results. We can also use reduce with Objects.
const a = [4, 2, 3, 4, 3, 2, 4, 1, 3, 2];
let res = a.reduce((acc, e) => {
acc.set(e, (acc.get(e) || 0) + 1);
return acc;
}, new Map());
console.log(res);
Output
{ '1': 1, '2': 3, '3': 3, '4': 3 }
4. Using for...of Loop Object (Similar to 2nd, only loop is different)
This approach uses the for...of loop to iterate through each element of the array and store frequencies in Map. We can also use this with Object.
const a = [4, 2, 3, 4, 3, 2, 4, 1, 3, 2];
let res = new Map();
for (const e of a) {
res.set(e, (res.get(e) || 0) + 1);
}
console.log(res);
Output
{ '1': 1, '2': 3, '3': 3, '4': 3 }