Count the Duplicates in an Array in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 4, 2024
4 min

banner

# Count the Duplicates in an Array in JavaScript

To count the duplicates in an array:

  1. Declare an empty object variable that will store the count for each value.
  2. Use the forEach() method to iterate over the array.
  3. On each iteration, increment the count for the value by 1 or initialize it to 1.
index.js
const arr = ['one', 'one', 'one', 'two', 'two', 'three']; const count = {}; arr.forEach(element => { count[element] = (count[element] || 0) + 1; }); // ๐Ÿ‘‡๏ธ {one: 3, two: 2, three: 1} console.log(count);

count duplicates in array

The code for this article is available on GitHub

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 value is already present as a key in the count object.

If the value is present, we increment it by 1, otherwise, we initialize it to 1.

We used the logical OR (||) operator to check if the key hasn't been initialized in the object.

If the accessor returns undefined, we initialize the value for the key to 0 + 1.

After the last iteration, the count object contains the elements of the array as keys and the number of their occurrences as values.

An alternative approach that helps us avoid the intermediary count variable is to use the Array.reduce() method.

# Count the Duplicates in an Array using Array.reduce()

This is a three-step process:

  1. Use the Array.reduce() method to iterate over the array.
  2. Use an empty object for the initial value of the accumulator.
  3. Increment the count if the element exists in the object, otherwise, initialize it to 1.
index.js
const arr = ['one', 'one', 'one', 'two', 'two', 'three']; const count = arr.reduce((accumulator, value) => { return { ...accumulator, [value]: (accumulator[value] || 0) + 1, }; }, {}); // ๐Ÿ‘‡๏ธ {one: 3, two: 2, three: 1} console.log(count);

count duplicates in array using array reduce

The code for this article is available on GitHub

This approach is very similar. However, it allows us to avoid declaring an empty object variable.

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

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

The value we return from the callback function gets passed as the accumulator on the next iteration.

We used destructuring assignment to unpack the key-value pairs from the accumulator into a new object where we override the current property by incrementing it or initializing it to 1.

After the last iteration, the object stores the elements of the array as keys and their occurrences in the array as values.

# Count the Duplicates in an Array using map and filter

You can also count the duplicates in an array by using the Array.map() and Array.filter() methods.

index.js
const arr = ['one', 'one', 'one', 'two', 'two', 'three']; const uniqueElements = [...new Set(arr)]; const count = uniqueElements.map(element => [ element, arr.filter(el => el === element).length, ]); // ๐Ÿ‘‡๏ธ [ [ 'one', 3 ], [ 'two', 2 ], [ 'three', 1 ] ] console.log(count);

count duplicates in array using map and filter

The code for this article is available on GitHub

We used the Set() constructor to remove the duplicates from the array and called the Array.map() method on the array of unique elements.

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

The map() method returns a new array containing the values returned from the callback function.

On each iteration, we return an array where the first element is the actual array element and the second is its number of occurrences in the array.

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

The filter() method returns a new array that only contains the elements that meet the condition.

On each iteration, we check if the current element is a duplicate.

The last step is to access the length property on the array of duplicates to get the count.

# Count the Duplicates in an Array using a for...of loop

You can also use a for...of loop to count the duplicates in an array.

index.js
const arr = ['one', 'one', 'one', 'two', 'two', 'three']; const count = {}; for (const element of arr) { count[element] = (count[element] || 0) + 1; } // ๐Ÿ‘‡๏ธ { one: 3, two: 2, three: 1 } console.log(count);

count duplicates in array using for of

The code for this article is available on GitHub

The for...of statement is used to loop over iterable objects like arrays, strings, Map, Set and NodeList objects and generators.

On each iteration, we check if the element exists as a key in the object and increment it if it does, otherwise, we initialize it to 1.

# Count the Duplicates in an Array using a for loop

You can also use a basic for loop to count the duplicates in an array.

index.js
const arr = ['one', 'one', 'one', 'two', 'two', 'three']; const count = {}; for (let index = 0; index < arr.length; index++) { count[arr[index]] = (count[arr[index]] || 0) + 1; } // ๐Ÿ‘‡๏ธ { one: 3, two: 2, three: 1 } console.log(count);

count duplicates in array using for loop

The code for this article is available on GitHub

The syntax for a for loop is quite verbose and we have to make use of the index to access the current array element.

Which approach you pick is a matter of personal preference. I'd use the Array.forEach() method as I find it quite direct and intuitive.

# 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