CC-12: Objects
Code Challenge
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 }// 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
Last updated