Created
July 19, 2012 07:43
-
-
Save ralphcrisostomo/3141412 to your computer and use it in GitHub Desktop.
Javascript: Count duplicates in an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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} | |
] | |
*/ |
Thanks for this @ralphcrisostomo! I implemented one change, though. I needed to use data repeatedly in different ways. The "delete copy[w]" on line 27 line really threw my data off. I changed it for "i++" and was successful in keeping my data intact. Thanks again!!
Had to search high and low for this solution, every tutorial and answer before was only outputting in the console. You are a legend! Thanks you!
@williamlsh those first three lines can be reduced to one via ES6 spread syntax!
let uniqueArr = [...new Set(arr)];
Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@davidnagli Thanks Buddy.. it really helped me with just one line code change.
appreciated