Javascript: Count duplicates in an array

Problem:

You have a javascript array that likely has some duplicate values and you would like a count of those values.

Solution:

Try this schnippet out.
 
function compressArray(original) {
 
	var compressed = [];
	// make a copy of the input array
	var copy = original.slice(0);
 
	// first loop goes over every element
	for (var i = 0; i < original.length; i++) {
 
		var myCount = 0;	
		// loop over every element in the copy and see if it's the same
		for (var w = 0; w < copy.length; w++) {
			if (original[i] == copy[w]) {
				// increase amount of times duplicate is found
				myCount++;
				// sets item to undefined
				delete copy[w];
			}
		}
 
		if (myCount > 0) {
			var a = new Object();
			a.value = original[i];
			a.count = myCount;
			compressed.push(a);
		}
	}
 
	return compressed;
};

It should go something like this:

var testArray = new Array("dog", "dog", "cat", "buffalo", "wolf", "cat", "tiger", "cat");
var newArray = compressArray(testArray);
 
/*
console: [
	Object { value="dog", count=2}, 
	Object { value="cat", count=3}, 
	Object { value="buffalo", count=1}, 
	Object { value="wolf", count=1}, 
	Object { value="tiger", count=1}
]
*/

I hope that’s useful to somebody.


4 Comments »

  1. The above example worked AWESOME…………………………….

    THANK U…….

    Comment by mvinay — January 16, 2012 @ 5:58 am

  2. Thank you so much! Great piece of code, you are a legend!

    Comment by Mark — February 3, 2012 @ 9:35 pm

  3. Awesome , just what i needed

    Comment by Danyal — March 6, 2012 @ 2:21 am

  4. Thanks a lot this helped me to finish my problem that i have been thinking how to do. I modified your code just so that it would return array insted of Object and its working great.

    Comment by Eddi — May 10, 2012 @ 8:51 am

Leave a comment