Skip to content

Instantly share code, notes, and snippets.

@williamlsh
Last active November 10, 2018 09:49
Show Gist options
  • Save williamlsh/223021b1793cfbd4963812f4e13ba2c7 to your computer and use it in GitHub Desktop.
Save williamlsh/223021b1793cfbd4963812f4e13ba2c7 to your computer and use it in GitHub Desktop.
/**
* 2018 William
* Array duplication counter
* Count duplicate elements in a array
*/
'use strict';
const caseArr = [1, 2, 2, 3, 3, 3];
const caseArr2 = ['Hello', 'Hello', 'hello', 'j', 'j', 'k'];
function countDup(arr = []) {
const set = new Set(arr);
const uniqueArr = Array.from(set);
if (uniqueArr.length === arr.length) return;
const map = new Map();
uniqueArr.forEach((uniqueVal) => {
let n = 0;
arr.forEach((val) => {
if (val === uniqueVal) {
n++;
}
});
map.set(uniqueVal, n);
});
console.log('newMap ', map);
for (const [key, val] of map) {
console.log(key, val);
}
}
countDup(caseArr);
countDup(caseArr2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment