Hi,
I am trying to rebuild the output of frequency counter which is in this case an object, alphabetically, I extracted the keys using Object.keys sorted them but I don’t know how to put them back with their corresponding values into an object, do I have to construct an algorithm or there are some methods that can do that?
function letterCount(str){
var frequency = {};
for (let char of str.toLowerCase()){
frequency[char]>0 ? frequency[char]++ : frequency[char] = 1;
}
let keys = Object.keys(frequency)
keys.sort((a,b)=>{
if(a<b) return -1; else return 1;
})
return frequency;
}
console.log(letterCount('Some string'))
Maybe convert the string in an array and sort the characters before adding properties to the object?
Maybe instead of an object create a multidimensional array? [["s", 2], ["a", 1], ...] - an array you can give a specific order
Slight amendment to what you already have (using entries rather than keys is probably easier):
function letterCount(str){
let frequency = {};
// I'm running this once rather than on every iteration of the loop:
const lcStr = str.toLowerCase();
// As before, count frequencies:
for (const char of lcStr){
char in frequency ? frequency[char]++ : frequency[char] = 1;
}
// I'm not sure why you don't just return `frequency` here, but anyway...
// Convert the frequency object to an array of [k, v] and sort:
const sortedFrequencies = Object.entries(frequency).sort(([a], [b]) => (a < b) ? -1 : (a > b) ? : 0);
// Reset frequency to empty:
frequency = {}
// Put the now-sorted k:v entries back in:
for (const [k, v] of sortedFrequencies) {
frequency[k] = v;
}
return frequency;
}
The question though is why you want to do this beyond it looking pretty in the console. Objects respect insertion order, but there isn’t really a good usecase for the extra computation: it’s very unusual to rely on the ordering of objects, that’s not what they’re designed for.
Alternative:
function letterCount(str){
// Build a map of characters like `{a: 0, b: 0, c: 0, ...}`
const frequencies = [...'abcdefghijklmnopqrsuvwxyz'].reduce((acc, char) => ({...acc, [char]: 0}), {});
// Loop through the string and increment the relevant field in the map:
for (const char of lcStr) frequencies[char.toLowerCase()]++;
return frequencies;
}