简体   繁体   中英

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)

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.

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM