To count occurrences of each element in an array in JavaScript, you can use any of these methods –
- Use the forEach loop to count occurrences of each element.
- Use the reduce() method to count occurrences of each element.
- Use a for loop to count occurrences of each element.
Let’s discuss each of these methods below in detail.
Count Occurrences Of Each Element In An Array In JavaScript
1. forEach Loop To Count Occurrences Of Each Element
The forEach loop is used to iterate over an array. It takes a callback function as an argument, which is invoked for each element in the array.
We can use the forEach loop to count occurrences of each element in an array by maintaining a count variable. The count variable is initialized to 0 and is incremented for each element in the array.
Consider the following example –
var arr = [1, 2, 2, 4, 4, 5, 4];
var count = {};
arr.forEach(element => {
if(count[element]) {
count[element]++;
}else{
count[element] = 1;
}
});
console.log(count);
Output –
{
1: 1,
2: 2,
4: 3,
5: 1
}
As you can see from the output, the count object contains the occurrence of each element in the array.
2. reduce() Method To Count Occurrences Of Each Element
The reduce() method is used to apply a function to each element in an array and reduce the array to a single value.
We can use the reduce() method to count occurrences of each element in an array in JavaScript by maintaining a count variable. The count variable is initialized to 0 and is incremented for each element in the array.
Consider the following example –
var arr = [‘a’, ‘b’, ‘a’, ‘c’, ‘d’];
var count = arr.reduce((acc, curr) => {
acc["‘" + curr + "‘"] ? acc["‘" + curr + "‘"]++ : (acc["‘" + curr + "‘"] = 1);
return acc;
}, {});
console.log(count);
Output –
{
‘a’: 2,
‘b’: 1,
‘c’: 1,
‘d’: 1
}
As you can see from the output, the count object contains the occurrence of each element in the array.
3. for Loop To Count Occurrences Of Each Element
A for loop can be used to iterate over an array. We can use a for loop to count occurrences of each element in an array in JavaScript by maintaining a count variable. The count variable is initialized to 0 and is incremented for each element in the array.
Consider the following example –
var arr = [1, 2, 2, 3, 4];
var count = {};
for(var i = 0; i < arr.length; i++) {
var element = arr[i];
if(count[element]) {
count[element]++;
}else{
count[element] = 1;
}
}
console.log(count);
Output –
{
1: 1,
2: 2,
3: 1,
4: 1
}
As you can see from the output, the count object contains the occurrence of each element in the array.
These are some of the methods that can be used to count occurrences of each element in an array. Try out each of these methods and see which one works best for you.