Affy
Affy

Reputation: 189

Check the repeated words in a string and keep a count in javascript

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)

Upvotes: 5

Views: 23235

Answers (3)

Pratap Sharma
Pratap Sharma

Reputation: 2753

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.

Upvotes: 5

terrymorse
terrymorse

Reputation: 7086

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>

Upvotes: 0

Alexandr Erokhov
Alexandr Erokhov

Reputation: 183

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

Upvotes: 3

Related Questions