I am trying to create a function that takes in a string as an input. This function should count each word and display a count number next to the individual word. The count should increase per iteration of the word.
Where the input is string == "this is this sample" and the expected output is "this(2) is(1) this(2) sample(1)"
This is what I have so far:
function wordCounter(string) {
const array = string.split(" ");
let count = 0;
for (let i = 0; i < array.length; i ) {
// if statement? //
}
}
From what I understand the string will need to be converted to an array to be looped over. However, I am having difficulty understanding how each specific word can have its own counter. I've also looked into .reduce(), but am having a hard time implementing it.
CodePudding user response:
My first raw idea would be to do something like this:
function wordCounter(string) {
const array = string.split(" ");
let count = {};
let result = '';
for (let i = 0; i < array.length; i ) {
if(count[array[i]]) {
count[array[i]] =1;
} else {
count[array[i]] = 1;
}
}
Object.keys(count).map(key => {
result = key '(' count[key] ') ';
});
return result;
}
console.log(wordCounter('hello this is a test'));
CodePudding user response:
This seems to work, but be aware it's coded with the intent of not counting blank spaces and includes punctuation/case when considering word count.
function wordCounter(string) {
var array = string.split(" ");
//"dictionary" is an object. We'll store words in it like properties.
var dictionary = {};
var final = "";
var current;
var currentCount;
for (let index = 0; index < array.length; index ) {
current = array[index];
//If the current array item isn't a blank...
if (current != "") {
//If the word isn't already in dictionary...
if (dictionary[current] == null) {
//We add it and set it to 1.
currentCount = 1;
dictionary[current] = currentCount;
}
//Otherwise...
else {
//We get the current value, add 1, and set the property to the new value.
currentCount = dictionary[current] 1;
dictionary[current] = currentCount;
}
//Now we append the word, parentheses, and current count.
final = current "(" currentCount ") ";
}
}
//Once the loops is done, if our word is greater than 0 characters, we slice the last one (the extra space from our last iteration).
if (final.length > 0) {
final = final.slice(0, -1);
}
//Print the final text.
alert(final);
}
window.addEventListener('load', function() {
wordCounter("This right here is this the sample of the sample you wanted. It's not the same as your sample, but it's a sample none the less.");
wordCounter("");
wordCounter(" ");
wordCounter(" this this and this ");
});
