JavaScript: Count the occurrences of elements in an array

Updated: March 8, 2023 By: Khue Post a comment

This concise, straight-to-the-point article shows you 3 different ways to count the occurrences of elements in a given array in JavaScript.

Using a loop

In the example below, we will use a for loop to iterate over the array and update the count for each element. We will create an object to store the count and print it out at the end.

Example:

const array = [
  'apple',
  'banana',
  'slingacademy.com',
  'apple',
  'slingacademy.com',
];
const count = {};

for (let i = 0; i < array.length; i++) {
  const element = array[i];
  count[element] = (count[element] || 0) + 1;
}

console.log(count);

Output:

{ apple: 2, banana: 1, 'slingacademy.com': 2 }

Using the reduce() method

In the following example, we will use the reduce() method to iterate over a given array and create an object that stores the count of each element.

Example:

const array = [
  'apple',
  'banana',
  'slingacademy.com',
  'apple',
  'slingacademy.com',
];

const count = array.reduce((acc, curr) => {
  acc[curr] = (acc[curr] || 0) + 1;
  return acc;
}, {});

console.log(count);

Output:

{ apple: 2, banana: 1, 'slingacademy.com': 2 }

Using the Array.filter() method and a callback function

In the example below, we will define a function called countOccurrences() that takes an array and a value as parameters and returns how many times that value appears in that array. The function uses the Array.filter() method to create a new array with only elements that are equal to the value parameter. Then it returns the length of this new array, which is equal to the number of occurrences of that value in that array.

The code:

// Define a function that takes an array and a value as parameters 
// and returns how many times that value appears in that array 
const countOccurrences = (array, value) => {
  var filteredArray = array.filter(function (element) {
    return element === value;
  });

  return filteredArray.length;
}

const arr = ['a', 'b', 'c', 'a', 'b', 'a', 'a', 'b', 'c', 'a', 'c', 'c'];
for (var i = 0; i < [...new Set(arr)].length; i++) {
  var uniqueElement = [...new Set(arr)][i];

  console.log(
    uniqueElement +
      ' occurs ' +
      countOccurrences(arr, uniqueElement) +
      ' times'
  );
}

Output:

a occurs 5 times
b occurs 3 times
c occurs 4 times

Conclusion

You’ve learned more than one technique to count the occurrences of elements in an array. This knowledge will help you in various situations, such as:

  • Grouping items in a shopping cart: When working with e-commerce applications, we may need to group items in a shopping cart based on their type, size, or color. We can use the methods described above to count the occurrences of each item and then group them accordingly.
  • Analyzing product reviews: If we have an array of product reviews where each review is a string, we can use the methods described above to count the occurrences of positive and negative words in the reviews. This is useful for tasks such as analyzing customer sentiment towards a product.

Done. Happy coding & have a nice day!