Javascript 中的经典字数统计算法

Toc*_*kwu 0 javascript arrays object ecmascript-6

拜托...伙计们,我哪里错了?

\n\n

经典的字数统计算法:给定一个字符串数组,返回一个 Map,其中每个不同字符串都有一个键,其值是该字符串在数组中出现的次数。

\n\n

wordCount(["a", "b", "a", "c", "b"]) \xe2\x86\x92 {"a": 2, "b": 2, "c": 1}

\n\n

wordCount(["c", "b", "a"]) \xe2\x86\x92 {"a": 1, "b": 1, "c": 1}

\n\n

wordCount(["c", "c", "c", "c"]) \xe2\x86\x92 {"c": 4}

\n\n

到目前为止我的代码

\n\n
function wordCount(arrayOfStrings) {\n    const map = {};\n\n    const arr = arrayOfStrings;\n\n    for (let i = 0; i < arr.length; i++) {\n\n        let arr2 = arr.charAt(i);\n\n        if (arr.indexOf(arr2) === arr.lastIndexOf(arr2)) {\n            map.push({\n                arr: arr2\n            });\n        }\n    }\n}\n\nwordCount(["a", "b", "a", "c", "b"])\n
Run Code Online (Sandbox Code Playgroud)\n\n

下面是我要通过的测试

\n\n
test(`Expect the wordCount of ["one", "fish", "two", "fish", "red", "fish", "blue", "fish"] to equal {one: 1, fish: 4, two: 1, red: 1, blue: 1}`, () => {\nexpect(wordCount([ \'one\', \'fish\', \'two\', \'fish\', \'red\', \'fish\', \'blue\', \'fish\' ])).toEqual({ one: 1, fish: 4, two: 1, red: 1, blue: 1 });\n});\n\ntest(`Expect the wordCount of ["str", "hell", "str", "str"] to equal {str: 3, hell: 1}`, () => {\nexpect(wordCount([ \'str\', \'hell\', \'str\', \'str\' ])).toEqual({ str: 3, hell: 1 });\n});\n\ntest(`Expect the wordCount of ["a", "b", "a", "c", "b"] to equal {"a": 2, "b": 2, "c": 1}`, () => {\nexpect(wordCount([ \'a\', \'b\', \'a\', \'c\', \'b\' ])).toEqual({ a: 2, b: 2, c: 1 });\n});\n\ntest(`Expect the wordCount of [1, "chair", "cane", "chair"] to equal {1: 1, chair: 2, cane: 1}`, () => {\nexpect(wordCount([ 1, \'chair\', \'cane\', \'chair\' ])).toEqual({ 1: 1, chair: 2, cane: 1 });\n});\n\ntest(`Expect the wordCount of ["ch", "chair", "cane", "chair", "ai", "ir"] to equal { ch: 1, chair: 2, cane: 1, ai: 1, ir: 1 }`, () => {\nexpect(wordCount([ \'ch\', \'chair\', \'cane\', \'chair\', \'ai\', \'ir\' ])).toEqual({ ch: 1, chair: 2, cane: 1, ai: 1, ir: 1 });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

Poi*_*nty 5

就目前情况而言,您的方法从根本上是错误的。您需要做的就是将数组中的每个字符串添加为属性(如果它还不是属性),并增加其值(如果是)。

function wordCount(arrayOfStrings) {
    const map = {};
    for (let i = 0; i < arrayOfStrings.length; ++i) {
      if (arrayOfStrings[i] in map)
        map[arrayOfStrings[i]]++;
      else
        map[arrayOfStrings[i]] = 1;
    }

    return map;
}
Run Code Online (Sandbox Code Playgroud)

该代码检查数组中的每个字符串,以查看它是否已经是正在构建的地图(普通对象)的属性。如果是,则该值递增;如果不是,则创建一个新属性并将其初始化为 1。

使用起来会更整洁一些.reduce()

function wordCount(arr) {
  return arr.reduce(function(map, word) {
    if (word in map)
      map[word]++;
    else
      map[word] = 1;
    return map;
  }, {});
}
Run Code Online (Sandbox Code Playgroud)