Day 2 - Q. Clean the following text and find the most frequent word (hint, use replace and regular expressions). #878
Unanswered
kattasahan
asked this question in
Q&A
Replies: 2 comments
|
We can replace the string with regular expression just as the hint mentioned. Here is my solution: |
0 replies
|
The existing solution keeps punctuation like A simpler one-liner for cleaning: const cleaned = sentence
.replace(/[^a-zA-Z\s]/g, '') // remove everything except letters and spaces
.replace(/\s+/g, ' ') // collapse multiple spaces into one
.trim()
.toLowerCase()For finding the most frequent word, this part requires loops (Day 6) and objects (Day 8), so it's normal if it feels out of scope for Day 2. Here's the full solution: const words = cleaned.split(' ')
const freq = {}
for (const word of words) {
freq[word] = (freq[word] || 0) + 1
}
const mostFrequent = Object.keys(freq).reduce((a, b) =>
freq[a] > freq[b] ? a : b
)
console.log(mostFrequent)The exercise likely expects you to revisit this part after Day 6-8, or it's intentionally placed as a stretch challenge to make you curious about what's coming. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
For above question i used so many functions and regular expressions to solve it, but as question is in Day-2, i think those are not ideal methods to solve
My Solution :
If anybody having a short and sweet solutions, Please share here...
Thanks in advance.
All reactions