Count the occurrence of each word in a phrase using javascript

和自甴很熟 提交于 2019-12-08 12:46:17

问题


For example for the input "olly olly in come free"

The program should return:

olly: 2 in: 1 come: 1 free: 1

The tests are written as:

var words = require('./word-count');

describe("words()", function() {
  it("counts one word", function() {
    var expectedCounts = { word: 1 };
    expect(words("word")).toEqual(expectedCounts);
  });

//more tests here
});
  1. How do I start in my word-count.js file? Create a method words() or a module Words() and make an expectedCount method in there and export it?

  2. Do I treat the string as an array or an object? In the case of objects, how do I start breaking them into words and iterate for the count?


回答1:


function count(str) {
  var obj = {};
  
  str.split(" ").forEach(function(el, i, arr) {
    obj[el] = obj[el] ? ++obj[el] : 1;
  });
  
  return obj;
}

console.log(count("olly olly in come free"));

This code should get just what you want.
For more understanding on the code I would advice you to go through array prototype functions and string prototype functions.
For simple understanding of what I`m doing here:

  1. Create a count function which returns an object of count of all occurrences of words.
  2. Split the string using split(" ") based on a space which gives an array.
  3. Use forEach method to iterate through all the elements in the spitted array.
  4. Ternary operator :? to check if value already exists, if it does increment by one or assign it to 1.

Array.prototype String.prototype




回答2:


Here's how you do it

word-count.js

function word-count(phrase){
    var result = {};  // will contain each word in the phrase and the associated count
    var words = phrase.split(' ');  // assuming each word in the phrase is separated by a space

    words.forEach(function(word){
        // only continue if this word has not been seen before
        if(!result.hasOwnProperty(word){
            result[word] = phrase.match(/word/g).length;
        }
    });

    return result;
}

exxports.word-count = word-count;


来源:https://stackoverflow.com/questions/26825786/count-the-occurrence-of-each-word-in-a-phrase-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!