Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How object works in javascript [duplicate]

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?

like image 365
Devesh Chaudhari Avatar asked Mar 05 '26 13:03

Devesh Chaudhari


1 Answers

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.

like image 50
Fullstack Guy Avatar answered Mar 08 '26 04:03

Fullstack Guy