Check how many times an Element appears in JS Array

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 and set its value to 0.
  2. Use the forEach() method to iterate over the array.
  3. Check if the current element is equal to the specific value.
  4. If the condition is met, increment the count 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 met, 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 it.

Alternatively, you can use the for...of loop.

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

  1. Declare a count variable and set its value to 0.
  2. Use a for...of loop to iterate over the array.
  3. Check if the current element is equal to the specific value.
  4. If the condition is met, increment the count by 1.
index.js
const arr = ['a', 'b', 'a', 'a']; let count = 0; for (const element of arr) { if (element === 'a') { count += 1; } } console.log(count); // 👉️ 3

We used the for...of loop to iterate over the array instead of the forEach() method.

On each iteration, we check if the current array element is equal to a specific value and if the condition is met, we increment the value of the count variable by 1.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.