Count Occurrences of All Items in an Array in JavaScript
Last Updated :
23 Jul, 2025
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.
JavaScript
//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.
JavaScript
//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.
JavaScript
//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.
JavaScript
//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
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.
JavaScript
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).
JavaScript
//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.
Count Occurrences Of All Elements in JavaScript
Visit Course
Similar Reads
How to Add Elements to a JavaScript Array? Here are different ways to add elements to an array in JavaScript.1. Using push() MethodThe push() method adds one or more elements to the end of an array and returns the new length of the array.Syntaxarray.push( element1, element2, . . ., elementN );JavaScriptconst arr = [10, 20, 30, 40]; arr.push(
3 min read
Create an Array of Given Size in JavaScript The basic method to create an array is by using the Array constructor. We can initialize an array of certain length just by passing a single integer argument to the JavaScript array constructor. This will create an array of the given size with undefined values.Syntaxconst arr = new Array( length );J
3 min read
Insert at the Beginning of an Array in JavaScript Following are different ways to add new elements at the beginning of an array1. Using the Array unshift() Method - Most Used:Adding new elements at the beginning of the existing array can be done by using the Array unshift() method. This method is similar to the push() method but it adds an element
2 min read
Remove Elements From a JavaScript Array Here are the various methods to remove elements from a JavaScript ArrayRemove elements from Array1. Using pop() methodThe pop() method removes and returns the last element of an array. This function decreases the length of the array by 1 every time the element is removed.javascriptlet a = ["Apple",
6 min read
Remove Duplicate Elements from JavaScript Array To Remove the elements from an array we can use the JavaScript set method. Removing duplicate elements requires checking if the element is present more than one time in the array. 1. Using JavaScript Set() - Mostly UsedThe JavaScript Set() method creates an object containing only unique values. To r
3 min read
How to Remove Multiple Elements from Array in JavaScript? Here are various methods to remove multiple elements from an array in JavaScript1. Using filter() MethodThe filter() method creates a new array with the elements that pass the condition. This method does not change the original array.JavaScriptlet a = [1, 2, 3, 4, 5]; let remove = [2, 4]; a = a.filt
3 min read
Insert at the Beginning of an Array in JavaScript Following are different ways to add new elements at the beginning of an array1. Using the Array unshift() Method - Most Used:Adding new elements at the beginning of the existing array can be done by using the Array unshift() method. This method is similar to the push() method but it adds an element
2 min read
Reverse an Array in JavaScript Here are the different methods to reverse an array in JavaScript1. Using the reverse() MethodJavaScript provides a built-in array method called reverse() that reverses the elements of the array in place. This method mutates the original array and returns the reversed array.JavaScriptlet a = [1, 2, 3
3 min read
JavaScript - Delete last Occurrence from JS Array These are the following ways to remove the last Item from the given array: 1. Using pop() Method (Simple and Easiest Method for Any Array) The pop() method is used to get the last element of the given array it can also be used to remove the last element from the given array. JavaScriptlet a = [34, 2
2 min read
Remove Empty Elements from an Array in JavaScript Here are different approaches to remove empty elements from an Array in JavaScript.1. Using array.filter() MethodThe array filter() method is used to create a new array from a given array consisting of elements that satisfy given conditions.array.filter( callback( element, index, arr ), thisValue )J
3 min read