CC-12: Objects
with Carmen Salas • 2024/10/23
Code Challenge
Write a function named
stringLengthsthat takes in an array of strings as an input, and returns an object, where the keys are all the strings in the array, and the value of each key represents the length of that string.
const stringLengths = (strArr) => {
let res = {};
strArray.forEach((str) => res[str] = str.length);
return res;
}
const instructors = ["Ben", "Motun", "Gonzolo", "Itzel"]
console.log(stringLengths(instructors)) // { Ben: 3, Motun: 5, Gonzolo: 7, Itzel: 5 }Write a function named
stringCountthat takes in an array of strings and returns an object where the keys are the strings from the array and the value of each key is a count of how many times the string appears in the object. If there are duplicate strings the values should reflect that.
// for each approach
const stringCount = (strArray) => {
let res = {};
strArray.forEach((str) => (res[str]) ? res[str]++ : res[str]=1);
return res;
}
// reduce approach
const stringCount = (strArray) => {
return strArray.reduce((res, str) => {
(res[str]) ? res[str]++ : res[str]=1
return res;
}, {});
}
const words = ["apple", "orange", "peach", "pear", "apple"]
console.log(stringCount(words)) // { apple: 2, orange: 1, peach: 1, pear: 1 }BONUS
Write a function named
highestFrequencyStringthat takes in an array of strings and returns the string with the highest frequency in the array and how many times it appears.
Last updated