Skip to content

Instantly share code, notes, and snippets.

@vuongtran
Last active June 6, 2021 22:57
Show Gist options
  • Save vuongtran/1c173ea65b58dd6fbf68de52b75da01e to your computer and use it in GitHub Desktop.
Save vuongtran/1c173ea65b58dd6fbf68de52b75da01e to your computer and use it in GitHub Desktop.
How to count duplicate value in an array in javascript
// #1 Solution
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}
// #2 Solution
function count() {
var arr = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
arr.sort();
var current = null;
var cnt = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] != current) {
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times<br>');
}
current = arr[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times');
}
}
count();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment