Categories
JavaScript Answers

How to Count Duplicate Values in an Array in JavaScript?

Spread the love

Sometimes, we want to count duplicate values in an array with JavaScript.

In this article, we’ll look at how to count duplicate values in an array with JavaScript.

Count Duplicate Values in an Array in JavaScript with forEach

We can use the JavaScript array forEach method to loop through the array we want to count the duplicates for and add the count of each item into an object.

For instance, we can write:

const arr = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"]
const counts = {};
arr.forEach((x) => {
  counts[x] = (counts[x] || 0) + 1;
});
console.log(counts)

We call forEach on arr with a callback that puts the array item x as a property of count .

Then we update counts[x] as the item x is being found from iteration.

If count[x] isn’t set yet, then 0 is set as the value of count[x] .

Then we get that counts is:

{
  "a": 3,
  "b": 2,
  "c": 2,
  "d": 1,
  "e": 2,
  "f": 1,
  "g": 1,
  "h": 3
}

where the keys are the arr items and the values are the counts of those items.

Conclusion

We can use the JavaScript array forEach method to loop through the array we want to count the duplicates for and add the count of each item into an object.

3 replies on “How to Count Duplicate Values in an Array in JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *