Determine how many words have a string consisting of one, 2, 3, etc. characters

The easiest of course did, but something I do not understand how to count the number of words. You can of course do it with if, but you’ll get a Hindu code, which you don’t really want.

const str = 'текст тееекст тексты тееекст тееекст' const word = str.split(' ') for (const a of word) { console.log(a.length) } 

  • "... consisting of one," - of what? - Igor
  • @Igor corrected - NyanSoldier
  • words count = word.length - Igor
  • @Igor You misunderstand, look, we have the line "one three three three three three" should be deduced that the word "three" was derived exactly 4 times - NyanSoldier
  • I did not "misunderstand", I did not understand at all. What are "one two three"? - Igor

1 answer 1

 var str = "один три два три три три"; var words = str.split(" "); var collect = {}; for (var i = 0; i < words.length; i++) { // если в словаре еще нет свойства words[i] заводим такое свойство с значением 0 if (!collect[words[i]]) collect[words[i]] = 0; // увеличиваем счетчик collect[words[i]]++; } // вывод результатов for(var word in collect) console.log(word, collect[word]); 

  • Thanks, can you explain how it works? What is the exclamation mark for? - NyanSoldier
  • @NyanSoldier added comments - Igor 8:38 pm
  • why! collect [words [i]], for what it needs "!" ? - NyanSoldier
  • @NyanSoldier if the object does not have a property with the same name, a call to this property returns undefined , which corresponds to false in the Boolean view - Igor
  • @NyanSoldier That is, if the collect object does not have a property named words[i] , we start such a property with a value of 0 . - Igor