By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Count Words with Maps - JavaScript task

+2 votes

You are tasked to count the number of words in a text using a Map, any combination of letters, digits and _ (underscore) should be counted as a word. The words should be stored in a Map - the key being the word and the value being the amount of times the word is contained in the text. The matching should be case insensitive. Print the words in a sorted order.

The input comes as an array of strings containing one entry - the text whose words should be counted. The text may consist of more than one sentence.


Far too slow, you're far too slow.

'far' -> 2 times
're' -> 1 times
'slow' -> 2 times
'too' -> 2 times
'you' -> 1 times

JS devs use Node.js for server-side JS. JS devs use JS. -- JS for devs --

'devs' -> 3 times
'for' -> 2 times
'js' -> 6 times
'node' -> 1 times
'server' -> 1 times
'side' -> 1 times
'use' -> 2 times

The output should be printed on the console - print each word in the map in the format "'<word>' -> <count> times", each on a new line.

asked in JavaScript category by user icabe

1 Answer

+1 vote

Here is my JS solution:

function countWordsWithMaps(inputLines) {
    let words = inputLines.join('\n').toLowerCase()
        .split(/[^A-Za-z0-9_]+/).filter(w => w != '');
    let wordsCount = new Map();
    for (let w of words)
        wordsCount.has(w) ? wordsCount.set(w,
            wordsCount.get(w) + 1) : wordsCount.set(w, 1);
    let allWords = Array.from(wordsCount.keys()).sort();
    allWords.forEach(w =>
        console.log(`'${w}' -> ${wordsCount.get(w)} times`));

//    "Far too slow, you're far too slow."

    "JS devs use Node.js for server-side JS. JS devs use JS. -- JS for devs --"


answered by user john7