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.

Answer 1
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

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

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.

Answer 4

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}

Answer 5

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

Answer 6

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!

Answer 7

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                                      
Answer 8

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]);
} 
Answer 9
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}`);
}
Answer 10

A combination of good answers:

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]);
    }
}  

Hope it's helpful.

Answer 11

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

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

Answer 12
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");
}   

}

Answer 13

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>"); 
}

Answer 14

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);
Answer 15

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));

Rent Charter Buses Company
READ ALSO
Set hidden input value without modifying the attribute

Set hidden input value without modifying the attribute

So many years in web development and still learning

390
How do I set property name to variable?

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?

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