3

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?

2
  • Look into this answer stackoverflow.com/questions/5525795/… Commented Mar 28, 2019 at 4:45
  • If you want to preserve order of arbitrary keys, use a Map. Object keys have a few rules around their ordering, have an ordering that isn’t specified to be respected by for…in loops, and overall aren’t well-suited to this task. Commented Mar 28, 2019 at 4:46

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

You can also write for (let [key, value] of map).
@Ry- yes, that is better. Thanks!
"Objects in JavaScript do not preserve the encounter order," [ if some keys can be evaluated as integers] (since ES2015) That is the very thing OP felt on.
@Kaiido can I add this in my answer?
Of course yes!. Well the actual rule is integers firsts, in ascending order, then strings in insertion order, then Symbols. But all functions aren't forced to respect these rules. Here is a good answer about it: stackoverflow.com/a/30919039/3702797

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.