In this article, we are going to discuss “How to Find The Count of Duplicates in an Array?”. Previously, we have discussed finding duplicate values from an array, and now we will see the number of duplicate values. This problem can be solved in multiple ways, but here we will see the most optimized way to solve it.
Solution:
Okay, for this we will use array reduce method and using an object key we will check if the key is present in the object, if yes then we will increment the value of the key else return 1. Let’s see code example to understand deeply:
<script>
const months = ['May','Feb','Feb','March','June','May','Feb','July','Aug']
const countOfDups = months.reduce((obj,months)=>{
if(obj[months] == undefined){
obj[months] = 1;
return obj;
}else{
obj[months]++;
return obj;
}
},{})
console.log(countOfDups);
</script>
So we have here a basic sample of code, here we have declared an array of months with some duplicate values. Then we added another constant to get results, in here we have used reduce method on month array, where we added two parameters obj and month array.
Now we need to check where obj[months] is undefined, since it is an object of the months array, so each element key will be undefined by default. We just put 1 and update the obj value for that element, once 1 will get assigned to each of the unique value, then if duplicate comes then this condition becomes false for it, and it will jump into else part.
In else part, we just need to increase the value by 1, so ultimately we will get the result of an array with its key values, these key values will refer to the number of duplicates in the array.
Output
{May: 2, Feb: 3, March: 1, June: 1, July: 1, …}
Aug
: 1
Feb : 3
July
: 1
June : 1
March : 1
May : 2
[[Prototype]]
: Object