请..。伙计们,我哪里出问题了?
经典的字数算法:给定一个字符串数组,为每个不同的字符串返回一个带键的Map,值为该字符串在数组中出现的次数。
wordCount("a“、"b”、"a“、"c”、"b")→{"a":2、"b":2、"c":1}
wordCount("c“、"b”、"a")→{"a":1、"b":1、"c":1}
wordCount("c","c")→{"c":4}
到目前为止我的代码
function wordCount(arrayOfStrings) {
const map = {};
const arr = arrayOfStrings;
for (let i = 0; i < arr.length; i++) {
let arr2 = arr.charAt(i);
if (arr.indexOf(arr2) === arr.lastIndexOf(arr2)) {
map.push({
arr: arr2
});
}
}
}
wordCount(["a", "b", "a", "c", "b"])及以下是我要通过的考试
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}`, () => {
expect(wordCount([ 'one', 'fish', 'two', 'fish', 'red', 'fish', 'blue', 'fish' ])).toEqual({ one: 1, fish: 4, two: 1, red: 1, blue: 1 });
});
test(`Expect the wordCount of ["str", "hell", "str", "str"] to equal {str: 3, hell: 1}`, () => {
expect(wordCount([ 'str', 'hell', 'str', 'str' ])).toEqual({ str: 3, hell: 1 });
});
test(`Expect the wordCount of ["a", "b", "a", "c", "b"] to equal {"a": 2, "b": 2, "c": 1}`, () => {
expect(wordCount([ 'a', 'b', 'a', 'c', 'b' ])).toEqual({ a: 2, b: 2, c: 1 });
});
test(`Expect the wordCount of [1, "chair", "cane", "chair"] to equal {1: 1, chair: 2, cane: 1}`, () => {
expect(wordCount([ 1, 'chair', 'cane', 'chair' ])).toEqual({ 1: 1, chair: 2, cane: 1 });
});
test(`Expect the wordCount of ["ch", "chair", "cane", "chair", "ai", "ir"] to equal { ch: 1, chair: 2, cane: 1, ai: 1, ir: 1 }`, () => {
expect(wordCount([ 'ch', 'chair', 'cane', 'chair', 'ai', 'ir' ])).toEqual({ ch: 1, chair: 2, cane: 1, ai: 1, ir: 1 });
});发布于 2019-08-20 00:36:36
从目前来看,你的做法是完全错误的。您所需要做的就是将数组中的每个字符串添加为一个属性(如果它还不是一个属性),如果是的话,则增加它的值。
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;
}该代码检查数组中的每个字符串,看看它是否已经是正在构造的映射(一个普通对象)的属性。如果是,则值将递增;如果不是,则创建一个新属性并将其初始化为1。
使用.reduce()会更整洁一些
function wordCount(arr) {
return arr.reduce(function(map, word) {
if (word in map)
map[word]++;
else
map[word] = 1;
return map;
}, {});
}发布于 2019-08-20 00:46:44
最简洁和最简单的方法是reduce
const wordCount = arr => arr.reduce((a, c) => ((a[c] = (a[c] || 0) + 1), a), {});发布于 2019-08-20 00:39:55
尝试这个(基于您的代码):
function wordCount(arrayOfStrings) {
const map = {};
const arr = arrayOfStrings;
for (let i = 0; i < arr.length; i++) {
map[arr[i]] = (map[arr[i]] || 0) +1;
}
return map;
}https://stackoverflow.com/questions/57565345
复制相似问题