Register Login

Count Number of Element Occurrences in JavaScript Array

Updated Oct 19, 2022

It is usually a typical operation for users to count the number of occurrences of a particular element in a JavaScript array. The element that users will use can be a number, string, object, or even a Boolean. In this article, we will go over different techniques to count the number of Element Occurrences of elements in a JavaScript Array.

  1. for-of loop
  2. for loop
  3. reduce()
  4. filter()
  5. lodash()
  6. Map Method

Method 1: Count the Number of Element Occurrences using a for-of loop:

Using a for loop is one of the standard methods that loop through an array and allows users to loop over each element of a JS array and return the desired operations given by the programmer. Thus, users can use this method to count the number of occurrences of any JS element in the array.

Perhaps, this is the best solution to count the number of element occurrences in an array.

JavaScript had a built-in for loop, as we all know, and it loops over every individual element on the array. But to make something a little easier, users can use its modification, i.e., the for-of loop.

Using this technique, users can directly access the value of the element itself rather than accessing each element by the specific index in the array.

Code Snippet:

const students = [23, 28, 18, 19, 28, 18, 28, 21, 23];
let a = 23;
let b = 0;
for (marks of students) {
  if (marks == a) {
		b++;
	}
};
console.log(b);
document.write('Occurance of Varaible '+ a + ' in array: ' + students + ': ' + b);

Output:

Run Code Snippet

Explanation:

In the above example, first of all, let us find how many times a particular element occurred in the array named "students." To execute this, users need to fix a counter variable to zero.

Here, we have used a counter variable named "b." Then, they need to use the for loop to loop through the JS array and increase the variable "b" by one each time they find the desired element they are searching.

When users use the for loop will loop through the entire array. The counter variable will hold the number of occurrences of the desired element.

Also, using for loop, users can find or count the number of element occurrences when they have an array of arrays.

Method 2: Using the simple for loop to count the number of occurrences of an element:

Using the basic for loop in JavaScript, users can also get the count of the occurrence of elements as the output.

Code Snippet:

const array = ['A', 'C', 'B', 'C', 'B', 'B'];
const demo = {};
for (let a = 0; a < array.length; a++) {
  const b = array[a];
  if (demo[b]) {
	demo[b] += 1;
  } else {
	demo[b] = 1;
  }
}
console.log(demo); 

document.write('Occurance of element in array: ' + array + ': ' + JSON.stringify(demo, null, 4));

Output:

Run Code Snippet

Explanation:

Here, we have used the basic for loop of JavaScript that will loop through the elements of the array. Then, we used a variable named "demo" that includes the for loop and the array.length property of JavaScript will set or return the number of elements in the given array.

Method 3: Using the reduce() to count the number of occurrences of an element:

The JavaScript reduce() method is one of the effective methods that users use to efficiently find the number of each element that occurred in a JS array using only a few lines of code. It takes the callback function and an initial value, which returns the count of the elements that occurred as an empty object so that users can populate it afterward.

Code Snippet:

const a = ["Hello", 6, "Python", "Hello", "Python", 2, 34, "Hello", "English", 34];
let b = a.reduce(function(c, d) {
	return(
		c[d] ? ++c[d] : (c[d] = 1),	c
	);
},
{});
console.log(b);
document.write('Occurance of element in array <br>' + a + ' <br> ' + JSON.stringify(b, null, 4))

Output:

Run Code Snippet

Explanation:

In the above code snippet, we used the JavaScript reduce() method that reduces the array into a single value and inside the method, we used a condition that checks and returns the number of occurrences of each element in the JS array.

In the output console, we can see the number of occurrences of each array element in the form of key-value pair ({element: number of occurrences, .....}).

Method 4: Using the filter() to count the number of occurrences of an element:

Apart from using the traditional for loop and reduce() method, which helped users to count the number of occurrences of a JS element, let us see some more techniques in this section of the article. The filter() method is one of the popular methods of filtering and counting the number of occurrences of a specific JS element.

Code Snippet:

const demo = ["Python", 6, "Python", "Hello", "Python", 2, 34, "Hello", "English", 34];
const a = (array, item) => {
	return array.filter((b) => b == item).length;
};

console.log(a(demo, "Python")); 
document.write('Occurance of element "Python" in array: ' + demo + '<br> "Python" : '+ a(demo, "Python"))

Output:

Run Code Snippet

Explanation:

In the above code snippet, we have used the filter() method of JavaScript that fills an array depending on the desired condition. Users can obtain the length using the length property from this too.

Method 5: Using the lodash () to count the number of occurrences of an element:

The last method we will discuss in this article is the lodash method. But generally, many experts recommend that users should avoid installing additional packages for only counting elements in an array. But if users already have the Lodash library pre-installed in their project, they can use this library which is of no harm to use while counting elements.

Code Snippet:

const myArray = ["Python", 6, "Python", "Hello", "Python", 2, 34, "Hello", "English", 34];
let lodash = _;
let elementOccurrences = _.countBy(myArray);
console.log(elementOccurrences);
document.write('Occurance of element in array ' + myArray + '<br>: ' + elementOccurrences)

Output:

Run Code Snippet

Explanation:

In the above code snippet, we have used the lodash JavaScript library that accepts an array and checks the occurrence of each element in the array. The .countBy() method of Lodash takes the values of the JS array and returns a new object. The object includes each element and its counts in key-value pairs.

Method 6: Using Map Javascript Map Method:

Code Snippet:

var array = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4]
const count = array.reduce((acc, e) => acc.set(e, (acc.get(e) || 0) + 1), new Map());
console.log([...count.entries()])

Output:

Run Code Snippet

Conclusion:

If users want to count the occurrence of a particular element in a JavaScript array, they can use the above methods mentioned in this article to count the number. But the for-of loop is better than the for loop, and it is preferable not to install any external library only to count the occurrence of an element.


×