[javascript] How to count duplicate value in an array in javascript

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.

This question is related to javascript arrays

The answer is


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!


Something like this:

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

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


Simple is better, one variable, one function :)

const counts = arr.reduce((acc, value) => ({
   ...acc,
   [value]: (acc[value] || 0) + 1
}), {});

Count the Letters provided in string

function countTheElements(){
    
    var str = "ssdefrcgfrdesxfdrgs";
    var arr = [];
    var count = 0;
    
    for(var i=0;i<str.length;i++){
        arr.push(str[i]);
        
    }
        arr.sort();
    for(var i=0;i<arr.length;i++){     
        if(arr[i] == arr[i-1]){
            count++;
        }else{        
            count = 1;        
        }
            if(arr[i] != arr[i+1]){
                console.log(arr[i] +": "+(count));
            }    
            
       }
    }
        countTheElements()

Declare an object arr to hold the unique set as keys. Populate arr by looping through the array once using map. If the key has not been previously found then add the key and assign a value of zero. On each iteration increment the key's value.

Given testArray:

var testArray = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];

solution:

var arr = {};
testArray.map(x=>{ if(typeof(arr[x])=="undefined") arr[x]=0; arr[x]++;});

JSON.stringify(arr) will output

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

Object.keys(arr) will return ["a","b","c","d","e","f","g","h"]

To find the occurrences of any item e.g. b arr['b'] will output 2


simplified sheet.js answare

_x000D_
_x000D_
var counts = {};_x000D_
var aarr=['a','b','a'];_x000D_
aarr.forEach(x=>counts[x]=(counts[x] || 0)+1 );_x000D_
console.log(counts)
_x000D_
_x000D_
_x000D_


var arr = ['a','d','r','a','a','f','d'];  

//call function and pass your array, function will return an object with array values as keys and their count as the key values.
duplicatesArr(arr);

function duplicatesArr(arr){
    var obj = {}
    for(var i = 0; i < arr.length; i++){
        obj[arr[i]] = [];
        for(var x = 0; x < arr.length; x++){
            (arr[i] == arr[x]) ? obj[arr[i]].push(x) : '';
        }
        obj[arr[i]] = obj[arr[i]].length;
    }

    console.log(obj);
    return obj;
}

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

CODE:

function getUniqueDataCount(objArr, propName) {
        var data = [];
        objArr.forEach(function (d, index) {
            if (d[propName]) {
                data.push(d[propName]);
            }
        });

        var uniqueList = [...new Set(data)];

        var dataSet = {};
        for (var i=0; i < uniqueList.length; i++) {
            dataSet[uniqueList[i]] = data.filter(x => x == uniqueList[i]).length;
        }
        
        return dataSet;
    }

Snippet

_x000D_
_x000D_
var data= [
          {a:'you',b:'b',c:'c',d:'c'},
          {a: 'you', b: 'b', c: 'c', d:'c'},
          {a: 'them', b: 'b', c: 'c', d:'c'},
          {a: 'them', b: 'b', c: 'c', d:'c'},
          {a: 'okay', b: 'b', c: 'c', d:'c'},
          {a: 'okay', b: 'b', c: 'c', d:'c'},
          ];
          
  console.log(getUniqueDataCount(data, 'a'));       
  
  function getUniqueDataCount(objArr, propName) {
        var data = [];
        objArr.forEach(function (d, index) {
            if (d[propName]) {
                data.push(d[propName]);
            }
        });

        var uniqueList = [...new Set(data)];

        var dataSet = {};
        for (var i=0; i < uniqueList.length; i++) {
            dataSet[uniqueList[i]] = data.filter(x => x == uniqueList[i]).length;
        }

        return dataSet;
    }
_x000D_
_x000D_
_x000D_



// Initial array
let array = ['a', 'b', 'c', 'd', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a'];

// Unique array without duplicates ['a', 'b', ... , 'h']
let unique = [...new Set(array)];

// This array counts duplicates [['a', 3], ['b', 2], ... , ['h', 3]] 
let duplicates = unique.map(value => [value, array.filter(str => str === value).length]);

Quickest way:

?omputational complexity is O(n).

_x000D_
_x000D_
function howMuchIsRepeated_es5(arr) {_x000D_
 const count = {};_x000D_
 for (let i = 0; i < arr.length; i++) {_x000D_
  const val = arr[i];_x000D_
  if (val in count) {_x000D_
   count[val] = count[val] + 1;_x000D_
  } else {_x000D_
   count[val] = 1;_x000D_
  }_x000D_
 }_x000D_
_x000D_
 for (let key in count) {_x000D_
  console.log("Value " + key + " is repeated " + count[key] + " times");_x000D_
 }_x000D_
}_x000D_
_x000D_
howMuchIsRepeated_es5(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);
_x000D_
_x000D_
_x000D_

The shortest code:

Use ES6.

_x000D_
_x000D_
function howMuchIsRepeated_es6(arr) {_x000D_
 // count is [ [valX, count], [valY, count], [valZ, count]... ];_x000D_
 const count = [...new Set(arr)].map(val => [val, arr.join("").split(val).length - 1]);_x000D_
_x000D_
 for (let i = 0; i < count.length; i++) {_x000D_
  console.log(`Value ${count[i][0]} is repeated ${count[i][1]} times`);_x000D_
 }_x000D_
}_x000D_
_x000D_
howMuchIsRepeated_es6(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);
_x000D_
_x000D_
_x000D_


var testArray = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];

var newArr = [];
testArray.forEach((item) => {
    newArr[item] = testArray.filter((el) => {
            return el === item;
    }).length;
})
console.log(newArr);

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

}   

}


let arr=[1,2,3,3,4,5,5,6,7,7]
let obj={}
for(var i=0;i<arr.length;i++){
    obj[arr[i]]=obj[arr[i]]!=null ?obj[arr[i]]+1:1 //stores duplicate in an obj

}
console.log(obj)
//returns object {1:1,:1,3:2,.....}

_x000D_
_x000D_
// new example._x000D_
var str= [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5];_x000D_
_x000D_
function findOdd(para) {_x000D_
  var count = {};_x000D_
  para.forEach(function(para) {_x000D_
  count[para] = (count[para] || 0) + 1;_x000D_
  });_x000D_
  return count;_x000D_
}_x000D_
_x000D_
console.log(findOdd(str));
_x000D_
_x000D_
_x000D_


It is simple in javascript using array reduce method:

_x000D_
_x000D_
const arr = ['a','d','r','a','a','f','d'];
const result =  arr.reduce((json,val)=>({...json, [val]:(json[val] | 0) + 1}),{});
console.log(result)
//{ a:3,d:2,r:1,f:1 }
_x000D_
_x000D_
_x000D_


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

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

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


Duplicates in an array containing alphabets:

_x000D_
_x000D_
var arr = ["a", "b", "a", "z", "e", "a", "b", "f", "d", "f"],_x000D_
  sortedArr = [],_x000D_
  count = 1;_x000D_
_x000D_
sortedArr = arr.sort();_x000D_
_x000D_
for (var i = 0; i < sortedArr.length; i = i + count) {_x000D_
  count = 1;_x000D_
  for (var j = i + 1; j < sortedArr.length; j++) {_x000D_
    if (sortedArr[i] === sortedArr[j])_x000D_
      count++;_x000D_
  }_x000D_
  document.write(sortedArr[i] + " = " + count + "<br>");_x000D_
}
_x000D_
_x000D_
_x000D_

Duplicates in an array containing numbers:

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


_x000D_
_x000D_
var string = ['a','a','b','c','c','c','c','c','a','a','a'];_x000D_
_x000D_
function stringCompress(string){_x000D_
_x000D_
var obj = {},str = "";_x000D_
string.forEach(function(i) { _x000D_
  obj[i] = (obj[i]||0) + 1;_x000D_
});_x000D_
_x000D_
for(var key in obj){_x000D_
  str += (key+obj[key]);_x000D_
}_x000D_
  console.log(obj);_x000D_
  console.log(str);_x000D_
}stringCompress(string)_x000D_
_x000D_
/*_x000D_
Always open to improvement ,please share _x000D_
*/
_x000D_
_x000D_
_x000D_


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

Create a file for example demo.js and run it in console with node demo.js and you will get occurrence of elements in the form of matrix.

var multipleDuplicateArr = Array(10).fill(0).map(()=>{return Math.floor(Math.random() * Math.floor(9))});
console.log(multipleDuplicateArr);

var resultArr = Array(Array('KEYS','OCCURRENCE'));

for (var i = 0; i < multipleDuplicateArr.length; i++) {
  var flag = true;
  for (var j = 0; j < resultArr.length; j++) {
     if(resultArr[j][0] == multipleDuplicateArr[i]){
       resultArr[j][1] = resultArr[j][1] + 1;
       flag = false;
      }
  }
  if(flag){
    resultArr.push(Array(multipleDuplicateArr[i],1));
  }
}

console.log(resultArr);

You will get result in console as below:

[ 1, 4, 5, 2, 6, 8, 7, 5, 0, 5 ] . // multipleDuplicateArr
[ [ 'KEYS', 'OCCURENCE' ],        // resultArr
  [ 1, 1 ],
  [ 4, 1 ],
  [ 5, 3 ],
  [ 2, 1 ],
  [ 6, 1 ],
  [ 8, 1 ],
  [ 7, 1 ],
  [ 0, 1 ] ]

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                                      

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

_x000D_
_x000D_
var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];_x000D_
var map = arr.reduce(function(prev, cur) {_x000D_
  prev[cur] = (prev[cur] || 0) + 1;_x000D_
  return prev;_x000D_
}, {});_x000D_
_x000D_
// map is an associative array mapping the elements to their frequency:_x000D_
document.write(JSON.stringify(map));_x000D_
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}
_x000D_
_x000D_
_x000D_


Single line based on reduce array function

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


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

Nobody responding seems to be using the Map() built-in for this, which tends to be my go-to combined with Array.prototype.reduce():

_x000D_
_x000D_
const data = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];_x000D_
const result = data.reduce((a, c) => a.set(c, (a.get(c) || 0) + 1), new Map());_x000D_
console.log(...result);
_x000D_
_x000D_
_x000D_

N.b., you'll have to polyfill Map() if wanting to use it in older browsers.


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.