CC-11: Objects
Code Challenge
const charCount = (str) => {
let res = {};
for (const char of str) {
// if the key "char" doesn't exist yet,
// --> set the value to 1
// otherwise
// --> +1 to the current value
res[char] = res[char] ? res[char] + 1 : 1;
}
return res;
};
const fellows = "marcy fellows";
console.log(charCount(fellows)); // returns { "m": 1, "a": 1, "r": 1, "c": 1, "y": 1, " ": 1, "f": 1, "e": 1, "l": 2, "o": 1, "w": 1, "s": 1 }const letterCount = (str) => {
let res = {};
// removes all non-letter characters in the string
str = str.replaceAll(/[^a-zA-Z]/g, () => "");
for (const char of str) {
// if the key "char" doesn't exist yet,
// --> set the value to 1
// otherwise
// --> +1 to the current value
res[char] = res[char] ? res[char] + 1 : 1;
}
return res;
};
const fellows = "marcy fellows";
console.log(letterCount(fellows)); // returns { "m": 1, "a": 1, "r": 1, "c": 1, "y": 1, " ": 1, "f": 1, "e": 1, "l": 2, "o": 1, "w": 1, "s": 1 }Last updated