Count Occurrences of All Items in an Array in JavaScript
Here are the different methods to count the occurrences of all items in an array in JavaScript
1. Using forEach() Method
The arr.forEach() method calls the provided function once for each element of the array. The provided function may perform any kind of operation on the elements of the given array.
//Driver Code Starts
let a = ['apple', 'banana', 'apple'];
const c = {};
//Driver Code Ends
a.forEach(ele => {
c[ele] = (c[ele] || 0) + 1;
});
//Driver Code Starts
console.log(c);
//Driver Code Ends
Output
{ apple: 2, banana: 1 }
In this example
- The code counts the occurrences of each element in the arr array.
- It iterates with forEach(), incrementing the count in the count object for each element.
2. Using reduce() Method
The Javascript arr.reduce() method iteratively applies a function to pairs of elements in an iterable, reducing them to a single result.
//Driver Code Starts
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'grape'];
//Driver Code Ends
let count = fruits.reduce((acc, curr) => {
acc[curr] = (acc[curr] || 0) + 1;
return acc;
}, {});
//Driver Code Starts
console.log(count);
//Driver Code Ends
Output
{ apple: 2, banana: 2, orange: 1, grape: 1 }
In this example
- The reduce method counts occurrences by iterating through the array.
- It adds each item to an object (acc) and increments its count or initializes it to 1 if it doesn’t exist.
3. Using filter() Method
The filter() method creates a new array with all elements that pass a test implemented by the provided function. It does not modify the original array.
//Driver Code Starts
let a = ['red', 'blue', 'green', 'red', 'yellow', 'blue', 'pink'];
let c = a.reduce((acc, curr) => {
acc[curr] = (acc[curr] || 0) + 1;
return acc;
}, {});
//Driver Code Ends
let dupli = Object.entries(c)
.filter(([key, value]) => value > 1)
.map(([key, value]) => ({ item: key, c: value }));
//Driver Code Starts
console.log(dupli);
//Driver Code Ends
Output
[ { item: 'red', count: 2 }, { item: 'blue', count: 2 } ]
In this example:
- Count items with reduce, filter those with counts > 1, and map them to show duplicates with their counts.
4. Using for...of Loop
The for...of loop iterates over the values of an iterable (like arrays, strings, etc.) and executes a block of code for each value.
//Driver Code Starts
let a = ['apple', 'banana', 'apple', 'orange', 'banana', 'grape'];
let count = {};
//Driver Code Ends
for (let item of a) {
count[item] = (count[item] || 0) + 1;
}
//Driver Code Starts
console.log(count);
//Driver Code Ends
Output
10 20 30 40
In this example
- The for...of loop iterates over each element in the array a.
- The count object tracks how many times each item appears.
- For each item, it either increments its count or initializes it to 1 if it's the first occurrence.
5. Using Lodash _.frequencies() Method
we are using the _.frequencies() method for calculating the occurance of all elements in the given array.
const _ = require('lodash');
let a = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana'];
let freq = _.countBy(a);
console.log(freq);
Output:
{
apple: 2,
banana: 3,
orange: 1
}
In this example
- _.countBy() takes an array and returns an object where the keys are the array elements, and the values are the counts of their occurrences.
6. Using Array.prototype.sort() Method
The Array.prototype.sort() method sorts the elements of an array in place according to a specified order (either ascending or descending).
//Driver Code Starts
const a = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana'];
//Driver Code Ends
const c = (a) => {
const Arr = a.slice().sort();
const count = {};
for (let ele of Arr) {
count[ele] = (count[ele] || 0) + 1;
}
return count;
};
//Driver Code Starts
console.log(c(a));
//Driver Code Ends
Output
{ apple: 2, banana: 3, orange: 1 }
In this example
- Sorting: arr.slice().sort() creates a sorted copy of the array.
- Counting: The for...of loop counts how many times each item appears in the sorted array.
- Result: The count object stores the occurrences of each item, which is returned by the function.