JavaScript Count String Occurrences in Array
In this article I will show you how I use JavaScript to traverse an array of strings. While doing so I will count the number of times that a specific string appears in the array. Then I will do the same for integers. There are a few ways to do this. The method that I use here is one that I find intuitive and elegant.
If you want to download the script in the article, you can do so below. The ZIP file contains 2 HTML files that you can run.
https://enfuzed.com/downloadables/find-occurences-in-array.zip
<p id="MyOutput"></p>
<script>
let MyArray = ["apple","cherry","pear","lemon","apple","banana","grapes","grapes","banana","pineapple","banana","cherry","apple","banana"];
let Counter = 0;
let LookingFor = "pear"; // change this to look for a different string
let TimesFound = 0;
for (Counter=0; Counter<MyArray.length; Counter++) {
if (MyArray[Counter] == LookingFor) {
TimesFound++;
}
}
document.getElementById("MyOutput").innerHTML = TimesFound;
</script>