# Count the Duplicates in an Array using JavaScript

Last updated: Jul 25, 2022

Photo from Unsplash

## Count the Duplicates in an Array#

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
```Copied!```const arr = ['one', 'two', 'one', 'one', 'two', 'three'];

const count = {};

arr.forEach(element => {
count[element] = (count[element] || 0) + 1;
});

// 👇️ {one: 3, two: 2, three: 1}
console.log(count);
``````

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 it is present, we increment it by `1`.

If the value is not present, we initialize it to `1`.

We used the logical OR (||) operator to check if the key has not been initialized in the array. 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 in the array as values.

An alternative approach, which helps us avoid the intermediary `count` variable is to use the Array.reduce method.

Use the `reduce()` method to count the duplicates in an array, passing it an empty object as the initial value for the accumulator. On each iteration, increment the count of the value in the object, or initialize the value to `1`.

index.js
```Copied!```const arr = ['one', 'two', 'one', 'one', 'two', 'three'];

const count = arr.reduce((accumulator, value) => {
return {...accumulator, [value]: (accumulator[value] || 0) + 1};
}, {});

// 👇️ {one: 3, two: 2, three: 1}
console.log(count);
``````

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

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

We passed an empty object as the initial value for the `accumulator` variable.

Whatever 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.