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

Q: Count Words in a Text - JavaScript task

+3 votes

You are tasked to count the number of words in a text using an object as an associative array, any combination of letters, digits and _ (underscore) should be counted as a word. The words should be stored in the object as properties - the key being the word and the value being the amount of times the word is contained in the text.

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.

Examples:

Input:
Far too slow, you're far too slow.

Output:
{"Far":1,"too":2,"slow":2,"you":1,"re":1,"far":1}


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

Output:
{"JS":3,"devs":2,"use":1,"Node":1,"js":1,"for":2,"server":1,"side":1}


The output should be printed on the console - the JSON representation of the object containing the words.

asked in JavaScript category by user hues

1 Answer

+2 votes

Here is the javascript code:

function countWords(input) {
    let text = input.join("\n");
    let words = text.split(/[^A-Za-z0-9_]+/)//^ in the beginning is NOT here
        .filter(w=>w != "");

    let wordCounts = {};
    for (let w of words) {
        wordCounts[w] ? wordCounts[w]++:
            wordCounts[w] = 1;
    }

    console.log(JSON.stringify(wordCounts));
}

//countWords([
//    "Far too slow, you're far too slow."
//]);

countWords([
    "JS devs use Node.js for server-side JS.-- JS for devs"
]);

 

answered by user icabe
...