OneBite.Dev - Coding blog in a bite size

count the number of occurrences of a specific element in an array in Javascript

Code snippet on how to count the number of occurrences of a specific element in an array in Javascript

  function countElement(array, element) {
    let count = 0;
    for (let i = 0; i < array.length; i++) {
      if (array[i] === element) {
        count++;
      }
    }
    return count;
  }

This code checks an array for a specific element and returns the number of times the element appears. The function takes two parameters: an array and the element to be counted. A variable called count is initiated and set to 0. A for loop is used to loop over the array, and an if statement is used to check if the element in the loop matches the input element. If so, the count is incremented by 1. Once the loop is finished, the count is returned.

javascript