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.
5 replies on “How to Count Duplicate Values in an Array in JavaScript?”
Helped alot, but i didnt get logic, after reading explanation also..pheww sry..and thanks to
still i m not getting (count||0)+1 concept
I was consused by this, too. I think it can be explained in Eloquent JS, if you are still curious. Read Chapter 1, under the heading “Short-circuiting of logical operators.” https://eloquentjavascript.net/01_values.html
So good. I’m not sure there exist any simpler solution for this task.
Best wishes, W
Thanks