4

I am trying to find repeated words in a string and keep a count of how many times it was repeated. How do I do it in javascript.

 let checkWords = "I am not gonna live forever, but I wanna live while I am alive"; 

I am looking for output like this I = 3, am = 2, not = 1 and so on, also is it possible to find the individual letter as I = 3, a = 6, m = 2.

I found a similar answer which I tried to use in my string, which works too but can anyone explain me why is the obj and undefined used here

let str = "I am not gonna live forever, but I wanna live while I am alive",
    split = str.split(" "),
    obj = {};

for (let i = 0; i < split.length; i++) {
  if (obj[split[i]] === undefined) {
    obj[split[i]] = 1;
  } else {
    obj[split[i]]++;
  }
}

console.log(obj)
Affy
  • 181
  • 1
  • 2
  • 13
  • Does this answer your question? [Counting occurrences of a word in a string Javascript](https://stackoverflow.com/questions/14914046/counting-occurrences-of-a-word-in-a-string-javascript) – ggorlen May 29 '20 at 15:03
  • Yes the question is similar but I am hoping for a bit detail in the answer. – Affy May 29 '20 at 15:07
  • There are many other dupes to look at as this is a very common operation. Search term: "js word frequency count". If you're looking for a bit of detail in the answer, you'll need to add a bit of detail in the question. There's no attempt here--it's customary to show a [mcve]. Please see [ask]. – ggorlen May 29 '20 at 15:12
  • @ggorlen Thank you but your help didn't helped me. – Affy May 29 '20 at 15:17
  • the object is used here to distinguish the words in the way that the key is the word and the value is the number of its occurrences. `obj[split[i]] === undefined` is used to check if the object contains the word that comes from the array: `split[i]` – zb22 May 29 '20 at 15:20
  • @zb22 Thanks... Understood that solves my question. – Affy May 29 '20 at 15:23

3 Answers3

5

Firstly convert the given string to an array. To do that use string.split("").

Secondly, create an map which will store word as key and count as value.

Now iterate through the stringArray and store the current word to the map. And increase the count for the word each time the word is found.

Check the below code.

let words = "I am not gonna live forever, but I wanna live while I am alive";

function countRepeatedWords(sentence) {
  let words = sentence.split(" ");
  let wordMap = {};

  for (let i = 0; i < words.length; i++) {
    let currentWordCount = wordMap[words[i]];
    let count = currentWordCount ? currentWordCount : 0;
    wordMap[words[i]] = count + 1;
  }
  return wordMap;
}

console.log(countRepeatedWords(words));

I hope this helps you.

Pratap Sharma
  • 2,633
  • 2
  • 18
  • 32
2
let checkWords = "I am not gonna live forever, but I wanna live while I am alive"

const newStr = checkWords.split(' ').reduce((acc,rec) => {
  return ({ ...acc, [rec]: (acc[rec] || 0) + 1 })
},{})

const newStr2 = checkWords.split('').reduce((acc,rec) => {
  return ({ ...acc, [rec]: (acc[rec] || 0) + 1 })
},{})

{newStr} for counter words {newStr2} for counter letters

0

How to count the number of times each word appears in a string:

  1. strip punctuation from the string with .replace()
  2. change all character to lowercase with .toLowerCase()
  3. convert string into array of words with .split()
  4. loop through each word (.forEach), adding it to a word count object

const result = document.getElementById('result');

let str = "I am not gonna live forever, but I wanna live while I am alive.";

// strip all punctuation from string
let strStripped = str.replace(/[,.!]/g, '');
result.innerHTML = `strStripped: "${strStripped}"\n`;

// separate string into array of lowercase words
let words = strStripped.toLowerCase().split(' ');
result.innerHTML += 'words: ' + JSON.stringify(words, null, 2);

// form object of word counts
let wordCounts = {};
words.forEach(word => {
  wordCounts[word] = (wordCounts[word] || 0) + 1;
});
result.innerHTML += '\nwordCounts: ' +
  JSON.stringify(wordCounts, null, 2);
<pre id="result"></pre>
terrymorse
  • 6,771
  • 1
  • 21
  • 27