Check how many times an Element appears in JS Array

avatar

Borislav Hadzhiev

Fri Oct 15 20212 min read

Check how many times an Element appears in an Array #

To check how many times an element appears in an array:

  1. Declare a count variable using the let keyword and set it to 0.
  2. Use the forEach() method to iterate over the array.
  3. On each iteration, check if the current element is equal to the specific value and if the condition is met, increment the value of the count variable by 1.
index.js
const arr = ['a', 'b', 'a', 'a']; let count = 0; arr.forEach(element => { if (element === 'a') { count += 1; } }); console.log(count); // ๐Ÿ‘‰๏ธ 3

The function we passed to the Array.forEach method gets called with each element in the array.

On each iteration we check if the element is equal to a specific value. If the condition is satisfied we increment the count variable by 1.

Note that we used the let keyword to declare the count variable. Had we used const, we wouldn't be able to reassign the variable and increment its value.

The forEach method is not supported in Internet Explorer. If you have to support the browser, use a basic for loop instead.
index.js
// Supported in IE const arr = ['a', 'b', 'a', 'a']; let count = 0; for (let index = 0; index < arr.length; index++) { if (arr[index] === 'a') { count += 1; } } console.log(count); // ๐Ÿ‘‰๏ธ 3

This code snippet achieves the same goal, however we use a basic for loop, instead of the forEach method.

I dislike how we have to interact with the array's index, even though the index is irrelevant for our use case.

This approach is a bit more verbose and harder to read, however it gets the job done if you have to support Internet Explorer.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee