Skip to content

Instantly share code, notes, and snippets.

@backslash112
Last active July 1, 2019 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save backslash112/642085eb2bcad3659ba083eed9bfa498 to your computer and use it in GitHub Desktop.
Save backslash112/642085eb2bcad3659ba083eed9bfa498 to your computer and use it in GitHub Desktop.
function countDuplicate(arr) {
let map = new Map();
arr.forEach(num => {
if (map.get(num) > 0) {
// set(key, value)
map.set(num, map.get(num) + 1);
} else {
// set(key, value)
map.set(num, 1);
}
});
let count = 0;
map.forEach((value, key) => {
console.log('key:', key, ',value:', value);
if (value > 1) {
count += (value - 1);
}
})
return count;
}
const res = countDuplicate([1, 4, 2, 4, 7, 1, 1, 9, 2, 3, 4, 1]);
console.log('result:', res);
/*
print:
key: 1 ,value: 4
key: 4 ,value: 3
key: 2 ,value: 2
key: 7 ,value: 1
key: 9 ,value: 1
key: 3 ,value: 1
result: 6
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment