Categories
JavaScript Answers

How to count duplicate value in an array in JavaScript?

Spread the love

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

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

How to count duplicate value in an array in JavaScript?

To count duplicate value in an array in JavaScript, we can put the count of each item in the array in an object.

For instance, we write

const counts = {};
const sampleArray = ["a", "a", "b", "c"];
sampleArray.forEach((x) => {
  counts[x] = (counts[x] ?? 0) + 1;
});
console.log(counts);

to loop through the sampleArray array by calling sampleArray.forEach with a callback that sets the counts[x] property to 0 if it doesn’t exist.

Or we add 1 to counts[x] if it already exists.

We do both with

counts[x] = (counts[x] ?? 0) + 1

Conclusion

To count duplicate value in an array in JavaScript, we can put the count of each item in the array in an object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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