Last active
November 10, 2018 09:49
-
-
Save williamlsh/223021b1793cfbd4963812f4e13ba2c7 to your computer and use it in GitHub Desktop.
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
/** | |
* 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