Reputation: 397
I am basically going to build a "keyword density" function.
The function is going to take text input from a textarea, so a basic string.
Let's say we have the string of My name is not Kevin this is not fun.
What I want to do, is write a function that finds two words groups that are duplicates.
In this example, the result would be is not
x2, as the word is not
is repeated twice and in the same order.
So instead of finding duplicate single words, for example, we want to find two words together that are duplicates.
Another example: Text string = What is your name? What is your hobby?
. The two combinations of groups of words are `What is, so that would count as x2.
So the function is going to find these duplicates inside this text(could be multiple groups), and store it in a way so that I can access it and display it in the UI.
What I have tried:
I am capable of doing this for a single word duplicate in the text, but I am unsure on how to start/go on when it comes to multiple words next to each other.
Any help is greatly appreciated!
Upvotes: 0
Views: 515
Reputation:
That can be done pretty easily in JavaScript. First lets make the string.
let testString = "The dog jumps and the dog barks
just some dummy text there.
Now if want to get all the words, we can use testString.split(" ")
this will split the string and return an array. Now just count how many times they occur.
Here's the code in action
let testString = "the dog jumps and the dog barks";
let testArray = testString.split(" ")
testArray.sort() //this will sort the array
function count() {
let current = null;
let cnt = 0;
for (var i = 0; i < testArray.length; i++) {
if (testArray[i] != current) {
if (cnt > 0) {
document.write(current + ' - ' + cnt + '<br>');
}
current = testArray[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.write(current + '-' + cnt);
}
}
count();
if this solution is your desired answer then please mark this answer by clicking the tick on the left. Thank you!
Upvotes: 1
Reputation: 23654
Here's a solution for finding 2-word phrases that uses map()
, reduce()
, Object.entries()
and Object.keys()
. It's easily extendable to find duplicates of any number of word groups.
let str = "What is your name? What is your hobby?";
let arr = str.split(" ");
let list = Object.entries(arr.reduce((acc, a, index) => {
if (index != 0) acc.push(arr[index - 1] + " " + arr[index])
return acc;
}, []).reduce((acc, a) => {
if (Object.keys(acc).indexOf(a) !== -1) acc[a]++;
else acc[a] = 1;
return acc;
}, {})).map(el => ({
phrase: el[0],
count: el[1]
}));
console.log(list)
Upvotes: 1