Introduction
When working with arrays in JavaScript, we frequently encounter situations that require us to count the number of occurrences of a specific element in that array - this element could be a string, object, number, or even a boolean.
In this article, we will go over several methods for counting the number of occurrences of an element or all elements in a JavaScript array. We'll also take a look at how to count the number of element occurrences in an array of arrays by flattening the array first.
How To Count Element Occurrences Using Loops
The for
loop is one of the standard methods to loop through an array. It allows us to loop over each element of an array and compare it to the element we are looking for. That way, we can count the number of occurrences of that element in an array. We can also use it to count the number of occurrences of all elements in the array, but we'll cover that case later in this article. For now, let's assume we want to find the number of occurrences of the specific element.
The Best Solution: for-of Loop
Obviously, JavaScript has a built-in for
loop we can use, but, to make things a bit easier, we can use its modification - the for-of
loop. That way, instead of accessing each element by its index in the array, we can access the value of the element itself.
Note: JavaScript ES2015 introduced the for-of
loop. It is an alternative to array.forEach()
method, previously used to iterate over each element of an array and apply some changes to each of them. The primary difference between for-of
and forEach()
is that the first is compatible with async
functions. In this article, we've opted to primarily use the for-of
loop instead of the forEach()
method just to be safe in an asynchronous scenario, but if you are not bothered with that, feel free to use forEach()
instead!
First of all, let's take a look at how many times a specific element occurs in an array. To accomplish this, we need to set the counter
variable to 0
, then loop through the array and increase the counter
by one each time we find the element we are looking for. When we loop through the entire array, the counter
will store the number of occurrences of the element we were searching for:
const allStudentsAge = [19, 22, 18, 19, 16, 18, 19, 21, 24];
let target = 19;
let counter = 0;
for (studentAge of allStudentsAge) {
if (studentAge == target) {
counter++;
}
};
console.log(counter); // 3
A situation where we have an array of arrays is a bit more complex. In that case, we will first have to flatten the array so all the elements comes into one array using the flat()
method:
const allStudentsAge = [
[1, 19],
[3, 4],
[5, 19],
[7, 8, 19],
[10, 11, 12, 13, 14, 15],
[19, 22, 18, 19, 16, 18, 19, 21, 24]
];
let target = 19;
let counter = 0;
for (studentAge of allStudentsAge.flat()) {
if (studentAge == target) {
counter++;
}
};
console.log(counter); // 6
This also works for arrays with elements of different data types. Let's create an example array with various data types and check to see if we can count the number of occurrences of a certain element:
const myArray = [false, 24, "English", false, "english", 22, 19, false, "English", 19];
Now, we can create a reusable function that counts the number of occurrences of the given element in the given array:
const checkOccurrence = (array, element) => {
let counter = 0;
for (item of array.flat()) {
if (item == element) {
counter++;
}
};
console.log(counter);
};
Let's check if the function we've created actually works:
checkOccurrence(myArray, false); // 3
checkOccurrence(myArray, 19); // 2
checkOccurrence(myArray, "english"); // 1
We've verified that there are three instances of the element false
and two instances of the element 19
, which is correct, but why is there only one occurrence of the element "english"
instead of three? This is due to case sensitivity of the function we've created - the best way to solve this is to convert all string elements to uppercase (or lowercase) before counting them:
const checkOccurrence = (array, element) => {
let counter = 0;
for (item of array.flat()) {
if (typeof item === "string") {
let newItem = item.toLowerCase();
if (newItem == element) {
counter++;
}
} else {
if (item == element) {
counter++;
}
}
};
console.log(counter);
};
When we now count the occurrences of the element "english"
, the checkOccurrence()
function returns 3
because it is no longer case-sensitive:
checkOccurrence(myArray, "english"); // 3
Alternative #1: for Loop
If you need to access the index of each element in an array for some reason, you can also use basic for
loop instead of for-of
:
const checkOccurrence = (array, element) => {
let counter = 0;
for (let i = 0; i <= array.length; i++) {
if (array[i] == element) {
counter++;
}
}
console.log(counter);
};
We can check that this gives us the same result as the same function created with for-of
loop:
checkOccurrence(myArray, false); // 3
checkOccurrence(myArray, 19); // 2
checkOccurrence(myArray, "english"); // 1
Alternative #2: forEach() Method
Another feasible alternative is to use the forEach()
method to iterate over all elements of an array:
const checkOccurrence = (array, element) => {
let counter = 0;
array.forEach()for (let i = 0; i <= array.length; i++) {
if (array[i] == element) {
counter++;
}
}
console.log(counter);
};
This would yield us the same result as the previous functions, but, again, be careful when using the forEach()
method in an asynchronous environment:
checkOccurrence(myArray, false); // 3
checkOccurrence(myArray, 19); // 2
checkOccurrence(myArray, "english"); // 1
Check the Number of Occurrences of All Elements
So far, we've seen how to count occurrences of a specific element. Now, let's see how to count occurrences of all elements and return both the element and the number of occurrences as an object.
To begin, we'll make an empty object to store each array element as the key and the number of occurrences as the value. We will then loop through the array using the for-of
loop, and on each iteration, we will increment the count for the specific element if it already exists in the object, or set the count to 1
otherwise:
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
const myArray = [false, 24, "English", false, "english", 22, 19, false, "English", 19];
let counter = {};
for (element of myArray.flat()) {
if (counter[element]) {
counter[element] += 1;
} else {
counter[element] = 1;
}
};
console.log(counter);
The previous code will output the object containing the number of occurrences of each element in the myArray
:
{
"19": 2,
"22": 1,
"24": 1,
"English": 2,
"english": 1,
"false": 3
}
Suppose we still want to avoid case sensitivity, we can do something like this:
const myArray = [false, 24, "English", false, "english", 22, 19, false, "English", 19];
let counter = {};
for (element of myArray.flat()) {
if (typeof element === "string") {
let newItem = element.toLowerCase();
if (counter[newItem]) {
counter[newItem] += 1;
} else {
counter[newItem] = 1;
}
} else {
if (counter[element]) {
counter[element] += 1;
} else {
counter[element] = 1;
}
}
});
console.log(counter);
This will output the object below:
{
"19": 2,
"22": 1,
"24": 1,
"false": 3,
"english": 3
}
How to Count Elements Occurrences Using reduce()
reduce()
is a powerful method that can be used to easily get the number of occurrences of each element in an array with only a few lines of code. It accepts a callback function and an initial value, which for us is an empty object so that we can populate it later:
const myArray = [false, 24, "English", false, "english", 22, 19, false, "English", 19];
let countObject = myArray.reduce(function (
count,
currentValue
) {
return (
count[currentValue] ? ++count[currentValue] : (count[currentValue] = 1),
count
);
},
{});
console.log(countObject);
This would output an object containing the elements as keys and the number of occurrences as values:
{
"19": 2,
"22": 1,
"24": 1,
"false": 3,
"English": 2,
"english": 1
}
How to Count Element Occurrences Using the filter() Method
In the previous section, we saw how to use the loops and reduce()
method for the various situations in which we might want to count the number of occurrences of elements in a JavaScript array. Aside from loops and reduce()
, we can also use other methods, such as the filter()
, to determine the number of occurrences of a specific element in an array.
To accomplish this, we will filter it, and it will then fill an array based on the condition, from which we will obtain the length using the length
property:
const myArray = [false, 24, "English", false, "english", 22, 19, false, "English", 19];
const itemCounter = (array, item) => {
return array.filter((currentItem) => currentItem == item).length;
};
console.log(itemCounter(myArray, 19)); // 2
Using Lodash to Count Element Occurrences
It is probably best not to install additional packages just for the purpose of counting elements in an array, but if we are already using the Lodash library in our project, there is no harm to use it for counting elements. The .countBy()
method in Lodash accepts an array and returns an object. This object contains elements and their counts as key-value pairs:
const myArray = [false, 24, "English", false, "english", 22, 19, false, "English", 19];
let lodash = _;
let elementOccurrences = _.countBy(myArray);
console.log(elementOccurrences);
This will give us an object:
{
"19": 2,
"22": 1,
"24": 1,
"false": 3,
"English": 2,
"english": 1
}
Conclusion
If you need to count the number of occurrences of elements in an array, probably your best bet is to use the for-of
loop as shown in this article. It is the async
safe, but still a very simple way to iterate over the whole array and count desired elements. We've also taken a look at other alternative approaches - basic for
loop, forEach()
, and filter()
method.
If you need to take a look at the number of occurrences of each element in an array, we've also got you covered - you can again use the for-of
loop. Also, you can use reduce()
method, or the Lodash library.