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?

  • Look into this answer https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – srimaln91 Mar 28 '19 at 04: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. – Ry- Mar 28 '19 at 04:46

1 Answers1

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.

Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
  • You can also write `for (let [key, value] of map)`. – Ry- Mar 28 '19 at 04:57
  • @Ry- yes, that is better. Thanks! – Fullstack Guy Mar 28 '19 at 04:59
  • "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 Mar 28 '19 at 05:09
  • @Kaiido can I add this in my answer? – Fullstack Guy Mar 28 '19 at 05:10
  • 1
    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: https://stackoverflow.com/a/30919039/3702797 – Kaiido Mar 28 '19 at 05:11