Count Occurrences of each Element in Array in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 2, 2024
7 min

banner

# Table of Contents

  1. Count Occurrences of each Element in an Array in JavaScript
  2. Count Occurrences of each Element in an Array using reduce()
  3. Count the Occurrences of each element in an array using forEach()
  4. Check how many times an Element appears in an Array using filter()
  5. Count the Occurrences of each element in an array using a for loop

# Count Occurrences of each Element in an Array in JavaScript

To count the occurrences of each element in an array:

  1. Declare a variable that stores an empty object.
  2. Use the for...of loop to iterate over the array.
  3. On each iteration, increment the count for the current element if it exists or initialize the count to 1.
index.js
// โœ… Count occurrences of each element in an array const arr = ['a', 'b', 'a', 'a', 'c', 'c']; const count = {}; for (const element of arr) { if (count[element]) { count[element] += 1; } else { count[element] = 1; } } console.log(count); // ๐Ÿ‘‰๏ธ {a: 3, b: 1, c: 2} console.log(count.a); // ๐Ÿ‘‰๏ธ 3 console.log(count.b); // ๐Ÿ‘‰๏ธ 1

count occurrences of each element in an array

The code for this article is available on GitHub

The same approach can be used if you only need to count the occurrences of a specific element in the array.

index.js
// โœ… Count occurrences of a specific element in an array const arr = ['a', 'b', 'a', 'a']; let count = 0; for (const element of arr) { if (element === 'a') { count += 1; } } console.log(count); // ๐Ÿ‘‰๏ธ 3

We declared a new variable and set it to an empty object.

The for...of loop allows us to iterate over the array.

Our if condition checks if the current array element is present as a key in the object.

If the element is present in the object, we increment the corresponding value, otherwise, we initialize the key to 1.

The keys in the object are the array elements and the values are the occurrences of each element in the array.

This approach also works if your array consists of numbers.

index.js
const arr = [1, 1, 1, 2, 3, 3]; const count = {}; for (const element of arr) { if (count[element]) { count[element] += 1; } else { count[element] = 1; } } console.log(count); // ๐Ÿ‘‰๏ธ {1: 3, 2: 1, 3: 2}

This seems a bit confusing as object keys can only be of type string or symbol in JavaScript.

However, you can still access the object's keys either way.

index.js
console.log(count[1]); // ๐Ÿ‘‰๏ธ 3 console.log(count['1']); // ๐Ÿ‘‰๏ธ 3
If you try to access the key of the object using a number, it will automatically get converted to a string under the hood.

You can also use the Array.reduce() method.

# Count Occurrences of each Element in an Array using reduce()

This is a three-step process:

  1. Use the Array.reduce() method to iterate over the array.
  2. Initialize the accumulator variable to an object.
  3. Increment the value for the current array element by 1 or initialize it to 1.
index.js
const arr = ['b', 'a', 'c', 'b', 'b', 'a']; const count = arr.reduce((accumulator, value) => { accumulator[value] = ++accumulator[value] || 1; return accumulator; }, {}); console.log(count); // ๐Ÿ‘‰๏ธ { b: 3, a: 2, c: 1 } console.log(count.a); // ๐Ÿ‘‰๏ธ 2 console.log(count.b); // ๐Ÿ‘‰๏ธ 3 console.log(count.c); // ๐Ÿ‘‰๏ธ 1

count occurrences of each element in array using reduce

The code for this article is available on GitHub

The function we passed to the Array.reduce() method gets called for each element in the array.

We initialized the accumulator variable as an empty object because that's what we passed as the second argument to the reduce() method.

On each iteration, we check if the current array element exists as a key in the object.

If the key exists, we increment its value by 1, otherwise, we initialize the key to 1.

You can also use a Map object instead of a regular object.

index.js
const arr = ['b', 'a', 'c', 'b', 'b', 'a']; const count = arr.reduce((accumulator, value) => { accumulator.set(value, (accumulator.get(value) || 0) + 1); return accumulator; }, new Map()); // ๐Ÿ‘‡๏ธ Map(3) { 'b' => 3, 'a' => 2, 'c' => 1 } console.log(count); console.log(count.get('a')); // ๐Ÿ‘‰๏ธ 2 console.log(count.get('b')); // ๐Ÿ‘‰๏ธ 3 console.log(count.get('c')); // ๐Ÿ‘‰๏ธ 1 // ๐Ÿ‘‡๏ธ [ 'b', 'a', 'c' ] console.log([...count.keys()]); // ๐Ÿ‘‡๏ธ [ 3, 2, 1 ] console.log([...count.values()]); // ๐Ÿ‘‡๏ธ [ [ 'b', 3 ], [ 'a', 2 ], [ 'c', 1 ] ] console.log([...count.entries()]);

We passed a Map object as the second argument to the reduce() function instead of a regular object.

On each iteration, we set the current element as a key in the Map and increment its value or initialize it to 1.

You can use the Map.get() method to get the number of occurrences of each element in the array.

The Map.keys() method returns the array elements and the Map.values() method returns the number of occurrences of each element in the array.

The Map.entries() method returns a two-dimensional array where the first element is the array value and the second element is the number of times the value is contained in the array.

If you have to do this often, define a reusable function.

index.js
function occurrencesOfEach(array) { const occurrences = array.reduce((accumulator, value) => { accumulator[value] = ++accumulator[value] || 1; return accumulator; }, {}); return occurrences; } const arr = ['b', 'a', 'c', 'b', 'b', 'a']; const result = occurrencesOfEach(arr); console.log(result); // ๐Ÿ‘‰๏ธ { b: 3, a: 2, c: 1 } console.log(result.a); // ๐Ÿ‘‰๏ธ 2 console.log(result.b); // ๐Ÿ‘‰๏ธ 3 console.log(result.c); // ๐Ÿ‘‰๏ธ 1

The function takes an array as a parameter and returns an object that stores the number of occurrences of each element in the array.

You can also use the Array.forEach() method.

# Count the Occurrences of each element in an array using forEach()

This is a four-step process:

  1. Declare a variable that stores an empty object.
  2. Use the forEach() method to iterate over the array.
  3. Check if each element is contained as a key in the object.
  4. If the condition is met, increment the value, otherwise, initialize the count to 1.
index.js
// โœ… count occurrences of each element in an array const arr = ['b', 'a', 'c', 'b', 'b', 'a']; const count = {}; arr.forEach(element => { if (count[element]) { count[element] += 1; } else { count[element] = 1; } }); // ๐Ÿ‘‡๏ธ { b: 3, a: 2, c: 1 } console.log(count);

count occurrences of each element in array using foreach

The code for this article is available on GitHub

The same approach can be used if you need to count the occurrences of a specific element in an array.

index.js
// โœ… count occurrences of a specific element in an array 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 current element is contained as a key in the object.

If the condition is met, we increment the key's value, otherwise, we initialize the value to 1.

If you have to do this often, define a reusable function.

index.js
function occurrencesOfEach(array) { const count = {}; array.forEach(element => { if (count[element]) { count[element] += 1; } else { count[element] = 1; } }); return count; } const arr = ['b', 'a', 'c', 'b', 'b', 'a']; const result = occurrencesOfEach(arr); console.log(result); // ๐Ÿ‘‰๏ธ { b: 3, a: 2, c: 1 } console.log(result.a); // ๐Ÿ‘‰๏ธ 2 console.log(result.b); // ๐Ÿ‘‰๏ธ 3 console.log(result.c); // ๐Ÿ‘‰๏ธ 1

The function takes an array as a parameter and returns an object containing the count of occurrences of each of the array elements.

# Check how many times an Element appears in an Array using filter()

This is a three-step process:

  1. Use the Array.filter() method to iterate over the array.
  2. Check if each element is equal to the specified value.
  3. Access the length property on the result.
index.js
const arr = ['a', 'b', 'a', 'a']; const count = arr.filter(element => { return element === 'a'; }).length; console.log(count); // ๐Ÿ‘‰๏ธ 3

check how many times element appears in array using filter

The code for this article is available on GitHub

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

On each iteration, we check if the current element is equal to the specified value and return the result.

The filter() method returns a new array containing only the values for which the callback function returned a truthy value.

index.js
const arr = ['a', 'b', 'a', 'a']; // ๐Ÿ‘‡๏ธ [ 'a', 'a', 'a' ] console.log( arr.filter(element => { return element === 'a'; }), );

The last step is to access the length property on the array to get the number of times the element appears in the array.

If you have to do this often, define a reusable function.

index.js
function countOccurrences(array, value) { return array.filter(element => { return element === value; }).length; } const arr = ['a', 'b', 'a', 'a']; console.log(countOccurrences(arr, 'a')); // ๐Ÿ‘‰๏ธ 3 console.log(countOccurrences(arr, 'b')); // ๐Ÿ‘‰๏ธ 1 console.log(countOccurrences(arr, 'c')); // ๐Ÿ‘‰๏ธ 0

The function takes an array and a value as parameters and returns the number of times the value is contained in the array.

You can also use a basic for loop to count the occurrences of each element in an array.

# Count the Occurrences of each element in an array using a for loop

This is a four-step process:

  1. Declare a variable that stores an empty object.
  2. Use a for loop to iterate over the array.
  3. Check if each element is contained as a key in the object.
  4. If the condition is met, increment the value, otherwise, initialize the count to 1.
index.js
const arr = ['a', 'b', 'a', 'a', 'c', 'c']; const count = {}; for (let index = 0; index < arr.length; index++) { const element = arr[index]; if (count[element]) { count[element] += 1; } else { count[element] = 1; } } console.log(count); // ๐Ÿ‘‰๏ธ {a: 3, b: 1, c: 2}
The code for this article is available on GitHub

This code sample achieves the same result. However, we use a basic for loop, instead of the for...of loop or the Array.forEach() method.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev