JSFiddle - React, Tailwind, and code Playground
by trentHarlem
JavaScript
function duplicateCount(str) {
let arr = str.toLowerCase().split('');
// reduce array to object
// key: value === unique letter: number of occurrences
const counterObject = arr.reduce((occurrences, letter) => {
occurrences[letter] = occurrences[letter] ? (occurrences[letter] + 1) : 1;
return occurrences;
}, {})
return Object.values(counterObject).filter(v => v > 1).length
}
function characterCounter(text) {
// convert string to array
let str = text.toLowerCase()
let arr = str.split('');
console.log(text, str, arr)
// reduce array to object
// key: value === unique letter: number of occurrences
//return
const counterObject = arr.reduce((occurrences, letter) => {
// 'occurrences' is the accumulator in our reduce function and with the initial value set to object {}. The object 'accumulates' properties each iteration.
// the value of the property(letter count) is then increased by 1 if it exists or set to 1 if it does not.
occurrences[letter] = occurrences[letter] ? (occurrences[letter] + 1) : 1;
// 'letter' is the current item of the array iterator.
// the ternary operator reads like:
// does our occurrences object already contain this [letter] ?
// if so, add 1 to its current value
// if not set its value to 1
//console.log('occurrences', occurrences)
//console.log('letter', letter)
// adding these console logs helps visualize the reduce function build the obect through each iteration based on these rules
return occurrences;
// outputing an object instead of an array avoids numeric indexing and makes this immediate comparison possible. the letters are the keys, the amount of times they appear in the loop is the value
}, {})
console.log(Object.entries(counterObject))
console.log(Object.values(counterObject).filter(v => v > 1))
console.log(Object.values(counterObject).filter(v => v > 1).length)
return Object.values(counterObject).filter(v => v > 1).length...