Reputation: 170
How can I get and display the count of each word in the string?
I am able to sort the words from most frequent, but I cannot display the count. The object: frequencies originally displayed the count (key).
I understand that Object.keys and the map() method may help me, but I am unsure how to include it the map method in my code.
Any help is much appreciated...
var stringtest = "Example: This is a string. I've excluded stopwords from becoming most frequent words. This is a string of words.";
function getFreq(string, cutOff){
var refineStr = string.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"").toLowerCase().replace(/ to\b| is\b| for\b| you\b| the\b|your\b|an\b| on\b| by\b|this\b|will\b| of\b| a\b/g, ""),
words = refineStr.split(" "),
frequencies = {},
word, frequency, i;
for(i = 0; i < words.length; i++){
word = words[i];
frequencies[" " + words[i]] = (frequencies[" " + words[i]] || 0) + 1;
//frequencies[word]++;
}
words = Object.keys(frequencies);
return words.sort(function (a,b)
{
return frequencies[b] - frequencies[a];}).slice(0, cutOff).toString();
}
document.getElementById("wordlist").innerHTML = getFreq(stringtest, 20);
Upvotes: 0
Views: 360
Reputation: 25319
There are a couple of things I would personally do differently. It would probably be easier to both read and update if you keep your exclusions in a separate array. Additionally, you don't need to regex for them, you can simply use a filter.
As for printing the results, a simple for..in loop will do.
const write = msg => {
document.body.appendChild(document.createElement('div')).innerHTML = msg;
};
const input = "Example: This is a string. I've excluded stopwords from becoming most frequent words. This is a string of words.";
const exclude = ["to", "is", "for", "you", "the", "your", "an", "on", "by", "this", "will", "of", "a"];
const lowerAlphaNum = input.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g, "").toLowerCase();
const filtered = lowerAlphaNum.split(" ").filter(word => exclude.indexOf(word) === -1);
const frequencies = {};
filtered.forEach(word => {
frequencies[word] = (frequencies[word] || 0) + 1;
});
const sortedArr = Object.keys(frequencies).map(word => ({
word: word,
frequency: frequencies[word]
})).sort((a, b) => b.frequency - a.frequency);
const trimmedArr = sortedArr.slice(0, 5);
trimmedArr.forEach(item => {
write(item.word + ': ' + item.frequency);
});
Upvotes: 1
Reputation: 5516
Using some code from this article:
var stringtest =
"Example: This is a string. I've excluded stopwords from becoming most frequent words. This is a string of words.";
function stringCount(string) {
var pattern = /(?=\S*['-])([a-zA-Z'-]+)|\w+/g,
matchedWords = string.match(pattern);
var counts = matchedWords.reduce(function(stats, word) {
if (stats.hasOwnProperty(word)) {
stats[word] = stats[word] + 1;
} else {
stats[word] = 1;
}
return stats;
}, {});
Object.keys(counts).map(function(key, index) {
document.getElementById("wordlist").innerHTML +=
`<tr>
<td>${key}</td>
<td>${counts[key]}</td>
</tr>`;
});
}
stringCount(stringtest);
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
<div class="row justify-content-center">
<div class="col-sm-10 col-md-8">
<table class='table table-striped'>
<thead class='thead-inverse'>
<tr>
<th>Word</th>
<th>Count</th>
</tr>
</thead>
<tbody id="wordlist"></tbody>
</table>
</div>
</div>
</div>
Upvotes: 1
Reputation: 503
"use strict";
let test = 'Example: This is a string. I\'ve excluded stop words from becoming most frequent words. This is a string of words.';
test = test.replace(/[.,:]/g, '');
test = test.replace(/ to\b| is\b| for\b| you\b| the\b|your\b|an\b| on\b| by\b|this\b|will\b| of\b| a\b/g, "");
test = test.split(' ');
let obj = {};
for (let i = 0, max = test.length; i < max; i++) {
if (!obj.hasOwnProperty([test[i]])) {
obj[test[i]] = 1;
continue;
}
obj[test[i]]++;
}
displayResult(obj, 30);
function displayResult(obj, maxAmount) {
let keys = Object.keys(obj);
let ul = document.createElement('ul');
if (maxAmount > keys.length) {
maxAmount = keys.length;
}
for (let i = 0; i < maxAmount; i++) {
let li = document.createElement('li');
li.innerHTML = keys[i] + ' : ' + obj[keys[i]];
ul.appendChild(li);
}
document.querySelector('#wordlist').appendChild(ul);
}
<div id="wordlist"></div>
Upvotes: 0