Introduction
When working with arrays in JavaScript, we regularly encounter conditions that require us to rely the variety of occurrences of a particular ingredient in that array – this ingredient might be a string, object, quantity, or perhaps a boolean.
On this article, we’ll go over a number of strategies for counting the variety of occurrences of a component or all components in a JavaScript array. We’ll additionally check out methods to rely the variety of ingredient occurrences in an array of arrays by flattening the array first.
How To Depend Ingredient Occurrences Utilizing Loops
The for
loop is likely one of the commonplace strategies to loop via an array. It permits us to loop over every ingredient of an array and evaluate it to the ingredient we’re searching for. That manner, we are able to rely the variety of occurrences of that ingredient in an array. We are able to additionally use it to rely the variety of occurrences of all components within the array, however we’ll cowl that case later on this article. For now, let’s assume we wish to discover the variety of occurrences of the precise ingredient.
The Greatest Resolution: for-of Loop
Clearly, JavaScript has a built-in for
loop we are able to use, however, to make issues a bit simpler, we are able to use its modification – the for-of
loop. That manner, as a substitute of accessing every ingredient by its index within the array, we are able to entry the worth of the ingredient itself.
Word: JavaScript ES2015 launched the for-of
loop. It’s a substitute for array.forEach()
technique, beforehand used to iterate over every ingredient of an array and apply some modifications to every of them. The first distinction between for-of
and forEach()
is that the primary is appropriate with async
features. On this article, we have opted to primarily use the for-of
loop as a substitute of the forEach()
technique simply to be secure in an asynchronous situation, however in case you are not bothered with that, be happy to make use of forEach()
as a substitute!
Initially, let’s check out what number of occasions a particular ingredient happens in an array. To perform this, we have to set the counter
variable to 0
, then loop via the array and enhance the counter
by one every time we discover the ingredient we’re searching for. Once we loop via the complete array, the counter
will retailer the variety of occurrences of the ingredient we had been trying to find:
const allStudentsAge = [19, 22, 18, 19, 16, 18, 19, 21, 24];
let goal = 19;
let counter = 0;
for (studentAge of allStudentsAge) {
if (studentAge == goal) {
counter++;
}
};
console.log(counter);
A state of affairs the place now we have an array of arrays is a little more advanced. In that case, we’ll first should flatten the array so all the weather comes into one array utilizing the flat()
technique:
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 goal = 19;
let counter = 0;
for (studentAge of allStudentsAge.flat()) {
if (studentAge == goal) {
counter++;
}
};
console.log(counter);
This additionally works for arrays with components of various information varieties. Let’s create an instance array with varied information varieties and examine to see if we are able to rely the variety of occurrences of a sure ingredient:
const myArray = [false, 24, "English", false, "english", 22, 19, false, "English", 19];
Now, we are able to create a reusable operate that counts the variety of occurrences of the given ingredient within the given array:
const checkOccurrence = (array, ingredient) => {
let counter = 0;
for (merchandise of array.flat()) {
if (merchandise == ingredient) {
counter++;
}
};
console.log(counter);
};
Let’s examine if the operate we have created truly works:
checkOccurrence(myArray, false);
checkOccurrence(myArray, 19);
checkOccurrence(myArray, "english");
We have verified that there are three situations of the ingredient false
and two situations of the ingredient 19
, which is right, however why is there just one prevalence of the ingredient "english"
as a substitute of three? This is because of case sensitivity of the operate we have created – one of the simplest ways to resolve that is to transform all string components to uppercase (or lowercase) earlier than counting them:
const checkOccurrence = (array, ingredient) => {
let counter = 0;
for (merchandise of array.flat()) {
if (typeof merchandise === "string") {
let newItem = merchandise.toLowerCase();
if (newItem == ingredient) {
counter++;
}
} else {
if (merchandise == ingredient) {
counter++;
}
}
};
console.log(counter);
};
Once we now rely the occurrences of the ingredient "english"
, the checkOccurrence()
operate returns 3
as a result of it’s now not case-sensitive:
checkOccurrence(myArray, "english");
Various #1: for Loop
If it’s essential to entry the index of every ingredient in an array for some purpose, you too can use fundamental for
loop as a substitute of for-of
:
const checkOccurrence = (array, ingredient) => {
let counter = 0;
for (let i = 0; i <= array.size; i++) {
if (array[i] == ingredient) {
counter++;
}
}
console.log(counter);
};
We are able to examine that this offers us the identical outcome as the identical operate created with for-of
loop:
checkOccurrence(myArray, false);
checkOccurrence(myArray, 19);
checkOccurrence(myArray, "english");
Various #2: forEach() Technique
One other possible various is to make use of the forEach()
technique to iterate over all components of an array:
const checkOccurrence = (array, ingredient) => {
let counter = 0;
array.forEach()for (let i = 0; i <= array.size; i++) {
if (array[i] == ingredient) {
counter++;
}
}
console.log(counter);
};
This could yield us the identical outcome because the earlier features, however, once more, watch out when utilizing the forEach()
technique in an asynchronous setting:
checkOccurrence(myArray, false);
checkOccurrence(myArray, 19);
checkOccurrence(myArray, "english");
Verify the Variety of Occurrences of All Components
To this point, we have seen methods to rely occurrences of a particular ingredient. Now, let’s have a look at methods to rely occurrences of all components and return each the ingredient and the variety of occurrences as an object.
To start, we’ll make an empty object to retailer every array ingredient as the important thing and the variety of occurrences as the worth. We are going to then loop via the array utilizing the for-of
loop, and on every iteration, we’ll increment the rely for the precise ingredient if it already exists within the object, or set the rely to 1
in any other case:
Try our hands-on, sensible information to studying Git, with best-practices, industry-accepted requirements, and included cheat sheet. Cease Googling Git instructions and really study it!
const myArray = [false, 24, "English", false, "english", 22, 19, false, "English", 19];
let counter = {};
for (ingredient of myArray.flat()) {
if (counter[element]) {
counter[element] += 1;
} else {
counter[element] = 1;
}
};
console.log(counter);
The earlier code will output the article containing the variety of occurrences of every ingredient within the myArray
:
{
"19": 2,
"22": 1,
"24": 1,
"English": 2,
"english": 1,
"false": 3
}
Suppose we nonetheless wish to keep away from case sensitivity, we are able to do one thing like this:
const myArray = [false, 24, "English", false, "english", 22, 19, false, "English", 19];
let counter = {};
for (ingredient of myArray.flat()) {
if (typeof ingredient === "string") {
let newItem = ingredient.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 may output the article under:
{
"19": 2,
"22": 1,
"24": 1,
"false": 3,
"english": 3
}
Depend Components Occurrences Utilizing cut back()
cut back()
is a strong technique that can be utilized to simply get the variety of occurrences of every ingredient in an array with solely a couple of strains of code. It accepts a callback operate and an preliminary worth, which for us is an empty object in order that we are able to populate it later:
const myArray = [false, 24, "English", false, "english", 22, 19, false, "English", 19];
let countObject = myArray.cut back(operate (
rely,
currentValue
) {
return (
rely[currentValue] ? ++rely[currentValue] : (rely[currentValue] = 1),
rely
);
},
{});
console.log(countObject);
This could output an object containing the weather as keys and the variety of occurrences as values:
{
"19": 2,
"22": 1,
"24": 1,
"false": 3,
"English": 2,
"english": 1
}
Depend Ingredient Occurrences Utilizing the filter() Technique
Within the earlier part, we noticed methods to use the loops and cut back()
technique for the varied conditions through which we would wish to rely the variety of occurrences of components in a JavaScript array. Except for loops and cut back()
, we are able to additionally use different strategies, such because the filter()
, to find out the variety of occurrences of a particular ingredient in an array.
To perform this, we’ll filter it, and it’ll then fill an array based mostly on the situation, from which we’ll acquire the size utilizing the size
property:
const myArray = [false, 24, "English", false, "english", 22, 19, false, "English", 19];
const itemCounter = (array, merchandise) => {
return array.filter((currentItem) => currentItem == merchandise).size;
};
console.log(itemCounter(myArray, 19));
Utilizing Lodash to Depend Ingredient Occurrences
It’s in all probability finest to not set up further packages only for the aim of counting components in an array, but when we’re already utilizing the Lodash library in our venture, there isn’t a hurt to make use of it for counting components. The .countBy()
technique in Lodash accepts an array and returns an object. This object comprises components 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 may give us an object:
{
"19": 2,
"22": 1,
"24": 1,
"false": 3,
"English": 2,
"english": 1
}
Conclusion
If it’s essential to rely the variety of occurrences of components in an array, in all probability your finest guess is to make use of the for-of
loop as proven on this article. It’s the async
secure, however nonetheless a quite simple strategy to iterate over the entire array and rely desired components. We have additionally taken a take a look at different various approaches – fundamental for
loop, forEach()
, and filter()
technique.
In case you want to try the variety of occurrences of every ingredient in an array, we have additionally bought you coated – you may once more use the for-of
loop. Additionally, you should utilize cut back()
technique, or the Lodash library.