How to Count the Occurrences of an Element in an Array in JavaScript?

Estimated read time 1 min read

In JavaScript, you can count the occurrences of an element in an array by using the Array.prototype.reduce() method. The reduce method takes a callback function as an argument, and this function is called for every element in the array. The function takes two arguments: an accumulator and the current value. You can use the accumulator to keep track of the count, and update it every time the current value matches the element you want to count.

Here’s an example:

function countOccurrences(array, element) {
  return array.reduce((acc, curr) => {
    return acc + (curr === element);
  }, 0);

You can call this function and pass in the array and the element you want to count as arguments:

let arr = [1, 2, 3, 1, 2, 1, 4];
let count = countOccurrences(arr, 1);
console.log(count); // 3

In this example, the function countOccurrences takes an array and an element as arguments. The reduce method is used to iterate over the array and count the occurrences of the element. The accumulator starts at 0 and is incremented by 1 every time the current value equals the element. The final value of the accumulator is returned, which is the count of occurrences.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply