我有两个数组,需要返回带有元素和计数器的map对象。它几乎完成了,但是我坚持使用计数器-对于计数器> 1的元素,它始终“未定义”。谁能帮我?
const stopWords = ['', 'a', 'the', 'and', 'or'];
const pageWords = ['HellO', 's', 'And', 'hellO', '', 'AnD', 'NAME', 'oR', 'apple', 'HELLO', 'aPple'];
const wordsCount = (words, stopWords) => {
const all = new Map();
const arr = words.map(word => word.toLowerCase())
.filter(word => !stopWords.includes(word))
.reduce((acc, word) => {
const count = all.has(word) ? acc[word] + 1 : 1;
all.set(word, count);
return acc;
}, {});
return all;
};
//what I need: [['hello', 3], ['s', 1], ['name', 1], ['apple', 2]]
你超级亲密。我相信现有代码的唯一问题是如何访问的当前计数word
。而不是使用,acc[word]
您应该使用all.get(word)
访问现有计数。像这样:
const stopWords = ['', 'a', 'the', 'and', 'or'];
const pageWords = ['HellO', 's', 'And', 'hellO', '', 'AnD', 'NAME', 'oR', 'apple', 'HELLO', 'aPple'];
const wordsCount = (words, stopWords) => {
const all = new Map();
const arr = words.map(word => word.toLowerCase())
.filter(word => !stopWords.includes(word))
.reduce((acc, word) => {
const count = all.has(word) ? all.get(word) + 1 : 1;
all.set(word, count);
return acc;
}, {});
return all;
};
console.log(Array.from(wordsCount(pageWords, stopWords)))
另外,此更改意味着您不再需要acc
,所以reduce
我认为aforEach
使得代码更易于阅读。像这样:
const stopWords = ['', 'a', 'the', 'and', 'or'];
const pageWords = ['HellO', 's', 'And', 'hellO', '', 'AnD', 'NAME', 'oR', 'apple', 'HELLO', 'aPple'];
const wordsCount = (words, stopWords) => {
const all = new Map();
words.map(word => word.toLowerCase())
.filter(word => !stopWords.includes(word))
.forEach(word => {
const count = all.has(word) ? all.get(word) + 1 : 1;
all.set(word, count);
});
return all;
};
console.log(Array.from(wordsCount(pageWords, stopWords)));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句