# How to count duplicate value in an array in javascript

3191
November 30, 2017, at 10:16 AM

Currently, I got an array like that:

``````var uniqueCount = Array();
``````

After a few steps, my array looks like that:

``````uniqueCount = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];
``````

How can I count how many a,b,c are there in the array? I want to have a result like:

``````a = 3
b = 1
c = 2
d = 2
``````

etc.

``````function count() {
array_elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
array_elements.sort();
var current = null;
var cnt = 0;
for (var i = 0; i < array_elements.length; i++) {
if (array_elements[i] != current) {
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times<br>');
}
current = array_elements[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times');
}
}
``````

Demo Fiddle

``````var counts = {};
your_array.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
``````

Something like this:

``````    uniqueCount = ["a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"];
var  count = {};
uniqueCount.forEach(function(i) { count[i] = (count[i]||0) + 1;});
console.log(count);``````

Use a simple for loop instead of forEach if you don't want this to break in older browsers.

I stumbled across this (very old) question. Interestingly the most obvious and elegant solution (imho) is missing: Array.prototype.reduce(...). All major browsers support this feature since about 2011 (IE) or even earlier (all others):

``````var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = arr.reduce(function(prev, cur) {
prev[cur] = (prev[cur] || 0) + 1;
return prev;
}, {});

// map is an associative array mapping the elements to their frequency:
document.write(JSON.stringify(map));
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}``````

You can do something like that:

``````uniqueCount = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = new Object();
for(var i = 0; i < uniqueCount.length; i++) {
if(map[uniqueCount[i]] != null) {
map[uniqueCount[i]] += 1;
} else {
map[uniqueCount[i]] = 1;
}
}
``````

now you have a map with all characters count

You can solve it without using any for/while loops ou forEach.

``````function myCounter(inputWords) {
return inputWords.reduce( (countWords, word) => {
countWords[word] = ++countWords[word] || 1;
return countWords;
}, {});
}
``````

Hope it helps you!

I think this is the simplest way how to count occurrences with same value in array.

``````var a = [true, false, false, false];
a.filter(function(value){
return value === false;
}).length
``````

You can have an object that contains counts. Walk over the list and increment the count for each element:

``````var counts = {};
uniqueCount.forEach(function(element) {
counts[element] = (counts[element] || 0) + 1;
});
for (var element in counts) {
console.log(element + ' = ' + counts[element]);
}
``````
``````var uniqueCount = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
// here we will collect only unique items from the array
var uniqueChars = [];
// iterate through each item of uniqueCount
for (i of uniqueCount) {
// if this is an item that was not earlier in uniqueCount,
// put it into the uniqueChars array
if (uniqueChars.indexOf(i) == -1) {
uniqueChars.push(i);
}
}
// after iterating through all uniqueCount take each item in uniqueChars
// and compare it with each item in uniqueCount. If this uniqueChars item
// corresponds to an item in uniqueCount, increase letterAccumulator by one.
for (x of uniqueChars) {
let letterAccumulator = 0;
for (i of uniqueCount) {
if (i == x) {letterAccumulator++;}
}
console.log(`\${x} = \${letterAccumulator}`);
}
``````

``````var count = {};
var arr = ['a', 'b', 'c', 'd', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a'];
var iterator = function (element) {
count[element] = (count[element] || 0) + 1;
}
if (arr.forEach) {
arr.forEach(function (element) {
iterator(element);
});
} else {
for (var i = 0; i < arr.length; i++) {
iterator(arr[i]);
}
}
``````

this one i found on github for more control over duplicate counting

https://gist.github.com/ralphcrisostomo/3141412

``````public class CalculateCount {
public static void main(String[] args) {
int a[] = {1,2,1,1,5,4,3,2,2,1,4,4,5,3,4,5,4};
Arrays.sort(a);
int count=1;
int i;
for(i=0;i<a.length-1;i++){
if(a[i]!=a[i+1]){
System.out.println("The Number "+a[i]+" appears "+count+" times");
count=1;
}
else{
count++;
}
}
System.out.println("The Number "+a[i]+" appears "+count+" times");
}
``````

}

Duplicates in an array containing alphabets:

``````var arr = ["a", "b", "a", "z", "e", "a", "b", "f", "d", "f"],
sortedArr = [],
count = 1;

sortedArr = arr.sort();

for (var i = 0; i < sortedArr.length; i = i + count) {
count = 1;
for (var j = i + 1; j < sortedArr.length; j++) {
if (sortedArr[i] === sortedArr[j])
count++;
}
document.write(sortedArr[i] + " = " + count + "<br>");
}``````

Duplicates in an array containing numbers:

``````var arr = [2, 1, 3, 2, 8, 9, 1, 3, 1, 1, 1, 2, 24, 25, 67, 10, 54, 2, 1, 9, 8, 1],
sortedArr = [],
count = 1;
sortedArr = arr.sort(function(a, b) {
return a - b
});
for (var i = 0; i < sortedArr.length; i = i + count) {
count = 1;
for (var j = i + 1; j < sortedArr.length; j++) {
if (sortedArr[i] === sortedArr[j])
count++;
}
document.write(sortedArr[i] + " = " + count + "<br>");
}``````

By using array.map we can reduce the loop, see this on jsfiddle

``````function Check(){
var arr = Array.prototype.slice.call(arguments);
var result = [];
for(i=0; i< arr.length; i++){
var duplicate = 0;
var val = arr[i];
arr.map(function(x){
if(val === x) duplicate++;
})
result.push(duplicate>= 2);
}
return result;
}
``````

To Test:

``````var test = new Check(1,2,1,4,1);
console.log(test);
``````

Single line based on reduce array function

``````const uniqueCount =  ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
const distribution = uniqueCount.reduce((acum,cur) => Object.assign(acum,{[cur]: (acum[cur] | 0)+1}),{});
console.log(JSON.stringify(distribution,null,2));``````

POPULAR ONLINE

### Set hidden input value without modifying the attribute

So many years in web development and still learning

390

Using ExtJS 42

479

### How do I set property name to variable?

I am working on an online class, for which we have to build a list tracker application using reactI have had issues when trying to set the state of one of my classes

281

### how do you create a stub/spy for an non-returned/parallel asynchronous function?

In this example, barStubcalled === false, presumably because the execution flow of fooStub does not wait for barStub to resolve

269