How to count duplicate value in an array in javascript

JavascriptArrays

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

const counts = {};
const sampleArray = ['a', 'a', 'b', 'c'];
sampleArray.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
console.log(counts)

Solution 2 - Javascript

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.

Solution 3 - Javascript

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:
console.log(map);
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}

EDIT:

By using the comma operator in an arrow function, we can write it in one single line of code:

var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = arr.reduce((cnt, cur) => (cnt[cur] = cnt[cur] + 1 || 1, cnt), {});

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

However, as this may be harder to read/understand, one should probably stick to the first version.

Solution 4 - Javascript

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

}

count();

http://jsfiddle.net/aQsuP/9/"> Demo Fiddle

You can use higher-order functions too to do the operation. See this answer

Solution 5 - Javascript

Simple is better, one variable, one function :)

const arr = ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];

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

console.log(counts);

Solution 6 - Javascript

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

Solution 7 - Javascript


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

Solution 8 - Javascript

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

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

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

Solution 9 - Javascript

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

Solution 10 - Javascript

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                                      

Solution 11 - Javascript

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!

Solution 12 - Javascript

// new example.
var str= [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5];

function findOdd(para) {
  var count = {};
  para.forEach(function(para) {
  count[para] = (count[para] || 0) + 1;
  });
  return count;
}

console.log(findOdd(str));

Solution 13 - Javascript

const obj = {};
const uniqueCount = [ 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a' ];
for (let i of uniqueCount) obj[i] ? obj[i]++ : (obj[i] = 1);
console.log(obj);

Solution 14 - Javascript

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

Solution 15 - Javascript

It is simple in javascript using array reduce method:

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 }

Solution 16 - Javascript

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

Solution 17 - Javascript

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

Solution 18 - Javascript

CODE:

function getUniqueDataCount(objArr, propName) {
    var data = [];
    if (Array.isArray(propName)) {
        propName.forEach(prop => {
            objArr.forEach(function(d, index) {
                if (d[prop]) {
                    data.push(d[prop]);
                }
            });
        });
    } else {
        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

var data= [
          {day:'Friday'   , name: 'John'      },
          {day:'Friday'   , name: 'John'      },
          {day:'Friday'   , name: 'Marium'    },
          {day:'Wednesday', name: 'Stephanie' },
          {day:'Monday'   , name: 'Chris'     },
          {day:'Monday'   , name: 'Marium'    },
          ];
          
console.log(getUniqueDataCount(data, ['day','name']));       
   
function getUniqueDataCount(objArr, propName) {
    var data = [];
    if (Array.isArray(propName)) {
        propName.forEach(prop => {
            objArr.forEach(function(d, index) {
                if (d[prop]) {
                    data.push(d[prop]);
                }
            });
        });
    } else {
        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;
}

Solution 19 - Javascript

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

Solution 20 - Javascript

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

Solution 21 - Javascript

simplified sheet.js answare

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

Solution 22 - Javascript

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.

Solution 23 - Javascript

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

Solution 24 - Javascript

var string = ['a','a','b','c','c','c','c','c','a','a','a'];

function stringCompress(string){

var obj = {},str = "";
string.forEach(function(i) { 
  obj[i] = (obj[i]||0) + 1;
});

for(var key in obj){
  str += (key+obj[key]);
}
  console.log(obj);
  console.log(str);
}stringCompress(string)

/*
Always open to improvement ,please share 
*/

Solution 25 - Javascript

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 ] ]

Solution 26 - Javascript

Quickest way:

Сomputational complexity is O(n).

function howMuchIsRepeated_es5(arr) {
	const count = {};
	for (let i = 0; i < arr.length; i++) {
		const val = arr[i];
		if (val in count) {
			count[val] = count[val] + 1;
		} else {
			count[val] = 1;
		}
	}

	for (let key in count) {
		console.log("Value " + key + " is repeated " + count[key] + " times");
	}
}

howMuchIsRepeated_es5(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);

The shortest code:

Use ES6.

function howMuchIsRepeated_es6(arr) {
	// count is [ [valX, count], [valY, count], [valZ, count]... ];
	const count = [...new Set(arr)].map(val => [val, arr.join("").split(val).length - 1]);

	for (let i = 0; i < count.length; i++) {
		console.log(`Value ${count[i][0]} is repeated ${count[i][1]} times`);
	}
}

howMuchIsRepeated_es6(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);

Solution 27 - Javascript

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

Solution 28 - Javascript

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

Solution 29 - Javascript

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,.....}

Solution 30 - Javascript

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

Solution 31 - Javascript

Example how to return the character that is most commonly used in the string.

function maxChar(str) {
	const charMap = {};

	let maxCharacter = '';
	let maxNumber = 0;

	for (let item of str) {
		charMap[item] = charMap[item] + 1 || 1;
	}

	for (let char in charMap) {
		if (charMap[char] > maxNumber) {
			maxNumber = charMap[char];
			maxCharacter = char;
		}
	}

	return maxCharacter;
}


console.log(maxChar('abcccccccd'))

Solution 32 - Javascript

Str= ['a','b','c','d','d','e','a','h','e','a'];
var obj= new Object();

for(var i = 0; i < Str.length; i++) {
 if(obj[Str[i]] != null) {
    obj[Str[i]] += 1;
} else {
    obj[Str[i]] = 1;
    }
}
console.log(obj);

Now you can get map of repeated items

Solution 33 - Javascript

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

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondetno29View Question on Stackoverflow
Solution 1 - JavascriptSheetJSView Answer on Stackoverflow
Solution 2 - JavascriptloxxyView Answer on Stackoverflow
Solution 3 - Javascriptisnot2badView Answer on Stackoverflow
Solution 4 - JavascriptVinay Pratap Singh BhadauriaView Answer on Stackoverflow
Solution 5 - JavascriptShannon HochkinsView Answer on Stackoverflow
Solution 6 - JavascriptdinigoView Answer on Stackoverflow
Solution 7 - JavascriptErik Martín JordánView Answer on Stackoverflow
Solution 8 - JavascriptaendraView Answer on Stackoverflow
Solution 9 - JavascriptnkronView Answer on Stackoverflow
Solution 10 - JavascriptDmytro KozlovskyiView Answer on Stackoverflow
Solution 11 - JavascriptPablo SouzaView Answer on Stackoverflow
Solution 12 - JavascriptRyan LuuView Answer on Stackoverflow
Solution 13 - JavascriptpHorekkaView Answer on Stackoverflow
Solution 14 - JavascriptRamiView Answer on Stackoverflow
Solution 15 - JavascriptYathin K RaoView Answer on Stackoverflow
Solution 16 - JavascriptAnkit GuptaView Answer on Stackoverflow
Solution 17 - JavascriptJaveed NazeerView Answer on Stackoverflow
Solution 18 - JavascriptARr0wView Answer on Stackoverflow
Solution 19 - JavascriptIlya KushlianskiView Answer on Stackoverflow
Solution 20 - Javascriptuser6160741View Answer on Stackoverflow
Solution 21 - JavascriptßãlãjîView Answer on Stackoverflow
Solution 22 - JavascriptXiaodan MaoView Answer on Stackoverflow
Solution 23 - JavascriptAli AdraviView Answer on Stackoverflow
Solution 24 - Javascriptsg28View Answer on Stackoverflow
Solution 25 - JavascriptJitendraView Answer on Stackoverflow
Solution 26 - JavascriptSerhii ZghamaView Answer on Stackoverflow
Solution 27 - JavascriptthapsView Answer on Stackoverflow
Solution 28 - Javascriptjidexl21View Answer on Stackoverflow
Solution 29 - JavascriptAbhiGaragView Answer on Stackoverflow
Solution 30 - Javascriptnano devView Answer on Stackoverflow
Solution 31 - JavascriptPanayot AngarevView Answer on Stackoverflow
Solution 32 - JavascriptTec ManiaView Answer on Stackoverflow
Solution 33 - JavascriptParv JohariView Answer on Stackoverflow