Last active
June 6, 2021 22:57
-
-
Save vuongtran/1c173ea65b58dd6fbf68de52b75da01e to your computer and use it in GitHub Desktop.
How to count duplicate value in an array in javascript
This file contains hidden or 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
// #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