I am working on code of frequncy counter where I count the frequncy of each word from a given string.
I am creating an object and making every word as key and it's frequency as value to make key-value pair.
function wordCount(str) {
tempStr = str.toUpperCase()
arr1 = tempStr.split(" ")
let frequencyConter1 = {}
for (let val of arr1) {
frequencyConter1[val] = (frequencyConter1[val] || 0) + 1
}
for (key in frequencyConter1) {
console.log(key, frequencyConter1[key])
}
}
wordCount("My name is Xyz 1991 He is Abc Is he allright")
1991 1
MY 1
NAME 1
IS 3
XYZ 1
HE 2
ABC 1
ALLRIGHT 1
why 1991 goes to first position in output?
It should be after XYZ, isn't it?
Objects in JavaScript do not preserve the encounter order, to preserve the insertion order of keys use the new Map object:
function wordCount(str) {
tempStr = str.toUpperCase();
arr1 = tempStr.split(" ");
let frequencyConter1 = new Map();
for (let val of arr1 ){
frequencyConter1.set(val, ((frequencyConter1.get(val) || 0) + 1) );
}
for( let [key, value] of frequencyConter1){
console.log(`${key} ${value}`);
}
}
wordCount("My name is Xyz 1991 He is Abc Is he allright")
Note: As @Kaiido mentioned, from ES2015 on wards in certain cases an order is imposed on the keys of the object. The order is integer like keys in ascending order, normal keys in insertion order and Symbols in insertion order but it does not apply for all iteration methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With