CC-11: Objects
with Carmen Salas • 2024/10/22
Code Challenge
Write a function named
charCount
that takes in a string and returns an object where the keys are letters in the string and the value of each key is a count of how many times the character appears in the string.
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 }
2+3 (BONUS: Refactor into for...off
). Write a function named letterCount
that takes in a string and returns an object where the keys are letters in the string and the value of each key is a count of how many times the character appears in the string, not including empty spaces.
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 }
Write a function named
vowelCount
that takes in a string and returns an object where the keys are letters in the given string that are vowels and the value of each vowel key is a count of how many times the character appears in the string.
const vowelCount = (str) => {
let res = {};
// finds only vowels, CASE-INSENSITIVE
str.match(/[aeiou]/gi).forEach((vowel) => {
// if the key "vowel" doesn't exist yet,
// --> set the value to 1
// otherwise
// --> +1 to the current value
res[vowel] = res[vowel] ? res[vowel] + 1 : 1;
});
return res;
};
const fellows = "marcy fellows";
console.log(vowelCount(fellows)); // returns {"a": 1, "o": 1, "e": 1}
Last updated