# Count the Duplicates in an Array using JavaScript

Sun Nov 14 20212 min read

## Count the Duplicates in an Array#

To count the duplicates in an array, declare an empty object variable that will store the count for each value and use the `forEach()` method to iterate over the array. On each iteration, increment the count for the value by `1` or initialize it to `1` if it hasn't been set already.

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.

For each element we check if the value in already present as a key in the `count` object. If it is present, we increment it by `1`.

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

The logical OR (||) operator is there 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 values of the array as keys pointing to their number of occurrences in the array.

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 occurrences of present values 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 to the previous one, 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've passed an empty object as the initial value for the `accumulator` variable.

Whatever we return from the callback function, gets passed as the accumulator for the next iteration.

We use destructuring assignment to unpack the key-value pairs from the accumulator into a new object and override the current property, by incrementing it or initializing it to `1`.

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