Write a function named stringLengths that 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.
Write a function named stringCount that 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.
Write a function named highestFrequencyString that takes in an array of strings and returns the string with the highest frequency in the array and how many times it appears.
// method mania
const highestFrequencyString = (strArray) => {
// so janky can we do better?
let res = {};
strArray.forEach((str) => (res[str]) ? res[str]++ : res[str]=1);
// var reuse because i'm a degenerate
res = Object.entries(res).sort((a,b) => b[1]-a[1])[0];
return `${res[0]} appears ${res[1]} times in the array.`
}
// for loop because you hate yourself
const highestFrequencyString = (strArray) => {
strArray.sort((a,b) => a <= b ? -1 : 1);
let max = 1;
let curr = 0;
let res = strArray[0];
for (let i = 0; i < strArray.length-1; i++) {
if (strArray[i] === strArray[i+1]) {
curr++;
} else {
if (max < ++curr) {
max = curr;
res = strArray[i];
}
curr = 0;
}
}
return `${res} appears ${max} times in the array.`
}
const fruits = ["apple", "orange", "apple", "peach", "pear", "apple", "peach"]
console.log(highestFrequencyString(fruits)); // "apple appears 3 times in the array."